我在Postgres(9.2)中有一个表格如下:
id | code | year
1 | A | 2014
1 | A | 2015
1 | A | 2016
2 | A | 2014
2 | A | 2015
2 | B | 2016
我正在尝试根据id
字段组合行。我可以通过自联接来实现,但是我试图避免在可能的情况下扫描表两次(可能是数百万行)。我想做这样的事情:
SELECT CASE year WHEN 2016 THEN code ELSE '' END AS code,
CASE year WHEN 2015 THEN code ELSE '' END AS prev_code
FROM tbl
GROUP BY id
HAVING year = 2015 OR year = 2016
理想情况下,输出看起来像这样:
code | prev_code
A | A (from id=1)
B | A (from id=2)
当我运行我提出的查询时,它告诉我year
需要在group by或一个聚合函数中。在互联网上有类似查询的例子,但它们似乎不适用于Postgres。知道如何在Postgres 9.2中做到这一点吗?
答案 0 :(得分:1)
你可以使用Lag window function:
Select Z.Code, Z.PrevCode
From (
Select Id, Code, Year
, lag( Code, 1 ) Over ( Partition By Id Order By Year ) As PrevCode
From tbl
Where Year In(2016,2015)
) As Z
Where Z.Year = 2016
答案 1 :(得分:1)
您可以按如下方式稍微修改您的查询:
SELECT MAX(CASE year WHEN 2016 THEN code ELSE '' END) AS code,
MAX(CASE year WHEN 2015 THEN code ELSE '' END) AS prev_code
FROM Table1 tbl
WHERE year IN(2015, 2016)
GROUP BY id;