查找SQL表中两个不同行的两列差异

时间:2014-05-16 19:34:06

标签: sql sql-server

我试图找出一个返回属于两个不同的单个表行的两列差异的查询

例如,我在表格中有以下数据

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

的AS GradeId=1,2相同
Bid of Id=1 - Offer of Id=2
Offer of Id=1- Bid of Id=2

Market

的AS GradeId=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。

1 个答案:

答案 0 :(得分:3)

使用row_number function

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