sql server - Finding difference of two columns from two different rows in an SQL table -
i trying figure out query returns difference of 2 columns belongs 2 different rows of single table
for example have following data in table
id market grade term bid offer 1 heavy abc jun14 -19.5 -17 2 heavy abc jul14 -20 -17.5 3 sour xyz jun14 -30 -17 4 sour xyz jul14 -32 -27
now, want following results
(as market
, grade
same id=1,2
)
bid of id=1 - offer of id=2 offer of id=1- bid of id=2
(as market
, grade
same id=3,4
)
bid of id=3 - offer of id=4 offer of id=3- bid of id=4
something following
market term bid offer heavy/abc jun14/jul14 (-19.5-(-17.5))=-2 (-17-(-20))=3 sour/xyz jun14/jul14 (-30-(-27))=-3 (-17-(-32))=15
what vest way ms sql.
using row_number function
create table things (id int, market varchar(30), grade varchar(30), term varchar(30), bid decimal, offer decimal) insert things values (1,'heavy','abc','jun14',-19.5 , -17) ,(2,'heavy','abc','jul14',-20 ,-17.5) ,(3,'sour','xyz','jun14',-30 , -17) ,(4,'sour','xyz','jul14',-32 , -27) ;with numbered ( select id, market, grade, term, bid, offer, row_number() on (partition market, grade order bid desc) things ) --select * numbered select r1.market + '/' + r1.grade market, r1.term + '/' + r2.term term, r1.bid - r2.offer [bid], r1.offer - r2.bid [offer] numbered r1 join numbered r2 on r1.market = r2.market , r1.grade = r2.grade , r1.i < r2.i
Comments
Post a Comment