Shash Talk
Shash Talk

Reputation: 21

Want to take the difference of two columns in Sql

I want to take the difference of columns of a table.we have column name as Planned_date so now I Want to take the difference of these two columns

A = Planned_Date of stop1 - Planned_Date of stop5

So how I can write the query to fetch the value of A below is the sample query I have written but somehow it is not working for me.

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')

Please help.

Upvotes: 1

Views: 66

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269793

Your query should work with a from clause:

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;

Personally, I would write this using conditional aggregation:

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';

Upvotes: 1

shrek
shrek

Reputation: 887

Try this -

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;

Upvotes: 2

Related Questions