我试图找出一个返回属于两个不同的单个表行的两列差异的查询
例如,我在表格中有以下数据
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
现在,我想要以下结果
(Market
Grade
和Id=1,2
相同
Bid of Id=1 - Offer of Id=2
Offer of Id=1- Bid of Id=2
(Market
Grade
和Id=3,4
相同
Bid of Id=3 - Offer of Id=4
Offer of Id=3- Bid of Id=4
像下面这样的东西
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
什么是背心方式来做MS SQL。
答案 0 :(得分:3)
create table things
(id int, Market varchar(30), Grade varchar(30), Term varchar(30), Bid decimal, Offer decimal)
insert into 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 as
(
select id, market, grade, term, bid, offer, row_number() OVER (Partition BY Market, Grade ORDER BY Bid desc) i
from things
)
--select * from numbered
select r1.market + '/' + r1.grade as Market, r1.term + '/' + r2.term as Term, r1.Bid - r2.Offer [Bid], r1.Offer - r2.Bid [Offer]
from numbered r1
join numbered r2 on r1.market = r2.market and r1.grade = r2.grade and r1.i < r2.i