按列分组以比较相似行之间的值

时间:2018-02-06 21:07:12

标签: sql sql-server

我试图改变这个

+----+---------+-------------------+-----------+
| id | year    | desc              | amount    |
+----+---------+-------------------+-----------+
|  1 | 2017    | car               | 500       |
|  2 | 2017    | car               | 550       |
|  1 | 2018    | car               | 490       |
|  2 | 2018    | car               | 550       |
|  1 | 2017    | house             | 200       |
|  2 | 2017    | house             | 300       |
|  1 | 2018    | house             | 210       |
|  2 | 2018    | house             | 320       |
|  1 | 2019    | house             | 290       |
|  2 | 2019    | house             | 325       |
+----+---------+-------------------+-----------+

进入类似的事情

+----+---------+---------+-------------------+-----------+-----------+
| id | year_0  | year_1  | desc              | amount_0  | amount_1  |
+----+---------+---------+-------------------+-----------+-----------+
|  1 | 2017    | 2018    | car               | 500       | 490       |
|  2 | 2017    | 2018    | car               | 550       | 550       |
|  1 | 2017    | 2018    | house             | 200       | 210       |
|  2 | 2017    | 2018    | house             | 300       | 320       |
+----+---------+---------+-------------------+-----------+-----------+

但是我很难通过描述获得两年和两年的分组。

1 个答案:

答案 0 :(得分:0)

您可以通过应用join

来达到结果
SELECT A.id,a.year year_0,b.year year_1, A.[desc], A.amount amount_0,B.amount amount_1 
FROM 
    (SELECT * FROM YourTable WHERE Year= Datepart(year,GETDATE())-1) AS A
INNER JOIN 
    (SELECT * FROM YourTable WHERE Year= Datepart(year,GETDATE())) AS B
ON A.id=B.id AND A.[desc]=B.[desc]