想要采取两列在SQL中的区别

时间:2018-06-25 18:10:32

标签: sql oracle

我想采用表格中各列的区别。我们将列名命名为Planned_date,所以现在我要采用这两列的区别

A = Planned_Date of stop1 - Planned_Date of stop5

那么我如何编写查询以获取A的值 下面是我编写的示例查询,但是某种程度上它对我不起作用。

select (select planned_arrival as val1 
        from shipment_stop 
         where stop_num = 1 
         and shipment_gid = 'IFFCO/LOGISTICS.L171009358')
       -
      (select planned_arrival as val2 
       from shipment_stop 
       where stop_num = 5 
       and shipment_gid = 'IFFCO/LOGISTICS.L171009358')

请帮助。

2 个答案:

答案 0 :(得分:2)

尝试一下-

SELECT
    s1.planned_arrival - s2.planned_arrival AS val
FROM
    shipment_stop s1,
    shipment_stop s2
WHERE
    s1.stop_num = 1
    AND s2.stop_num = 5
    AND s1.shipment_gid = 'IFFCO/LOGISTICS.L171009358'
    AND s1.shipment_gid = s2.shipment_gid;

答案 1 :(得分:1)

您的查询应使用from子句:

select (select planned_arrival as val1 
        from shipment_stop 
         where stop_num = 1 
         and shipment_gid = 'IFFCO/LOGISTICS.L171009358')
       -
      (select planned_arrival as val2 
       from shipment_stop 
       where stop_num = 5 
       and shipment_gid = 'IFFCO/LOGISTICS.L171009358')
from dual;

我个人将使用条件聚合来编写:

select (max(case when stop_num = 1 then planned_arrival end) -
        max(case when stop_num = 5 then planned_arrival end)
       )
from shipment_stop 
where stop_num in (1, 5) and 
      shipment_gid = 'IFFCO/LOGISTICS.L171009358';