比较同一个sql表中两行的数据

时间:2016-12-08 00:21:04

标签: sql sql-server tsql sql-server-2008-r2

我试图找出同一个表中两行之间的差异。无法找到正确的查询。例如,我有

Year   Item      Qty    Amount 
------------------------------
2014   Shoes     500     2500 
2014   Ties      300      900 
2014   Pants     200     4000 
2015   Shoes     600     3000 
2015   Ties      200      600

我试图找出从去年到今年增加(或减少)的数量。我总是只有两年时间来比较。查询结果应如下所示:

Items   Qty Diff   Amount Diff 
------------------------------
Shoes      100         500 
Ties    (-100)      (-300) 
Pants     Null        Null 

查询应该是什么样的?

3 个答案:

答案 0 :(得分:5)

如果您想要包含所有内容,那么您可以使用FULL OUTER JOIN,如果只是具有较早年份LEFT OUTER JOIN的{​​{1}},如果您想要包含早期和后续年份的那个,那么{{ 1}}。

INNER JOIN

答案 1 :(得分:1)

使用滞后函数是最佳方法。

SELECT  [Year], [Item], [Qty], [Amount],
       [Qty] - LAG([Qty]) OVER (PARTITION BY [Item] ORDER BY [Year]) [QtyDiff],
       [Amount] - LAG([Amount]) OVER (PARTITION BY [Item] ORDER BY [Year]) [AmountDiff]
FROM [ItemTable] it
order BY [Year] DESC, [Item];

希望这有帮助。

答案 2 :(得分:0)

以下是必需的查询:

SET @YEAR1 = '2014';
SET @YEAR2 = '2015';

SELECT 
      Item,
      if(count(*)>1,sum(if(Year=@YEAR2,Qty,-Qty)),NULL) as 'Qty Diff',                                 
      if(count(*)>1,sum(if(Year=@YEAR2,Amount,-Amount)),NULL) as 'Amount Diff' 
FROM 
      table 
WHERE 
      Year IN (@YEAR1,@YEAR2) 
group by Item;