postgresql-group by-complex query

问题描述 投票:3回答:1

这是我的桌子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  |  -
postgresql
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.