postgresql-group by-complex query

时间:2016-03-28 12:13:18

标签: postgresql

这是我的桌子TheTable的样子

ColA  | ColB  | 
------+-------+------
abc   | 2005  | 
abc   | 2010  | 
def   | 2009  | 
def   | 2010  | 
def   | 2011  | 
abc   | 2012  | 

我想写一个查询来返回这个结果:

ColA  | ColB  | ColC
------+-------+------
abc   | 2005  | 2010
def   | 2009  | 2011
abc   | 2012  |  -

1 个答案:

答案 0 :(得分:0)

我相信您可以使用窗口函数和嵌套子查询来获得所需的结果:

select "ColA"
, max(case when parity = 0 then "ColB" end) as "ColB"
, max(case when parity = 1 then "ColB" end) as "ColC"
from (
 select * 
  , (rank() over(partition by "ColA" order by "ColB" asc) - 1)
  , (rank() over(partition by "ColA" order by "ColB" asc) - 1) / 2 as result_row
  , (rank() over(partition by "ColA" order by "ColB" asc) - 1) % 2 as parity

 from TheTable ) t

GROUP BY "ColA", result_row