gpt4 book ai didi

postgresql-group by- 复杂查询

转载 作者:行者123 更新时间:2023-11-29 11:51:41 28 4
gpt4 key购买 nike

这是我的表格 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 | -

最佳答案

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

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

关于postgresql-group by- 复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262065/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com