我可以在postgresql中获得此结果吗?

时间:2016-10-25 23:56:44

标签: postgresql

我有一个带有

的table1

enter image description here

是否可以拥有table2:

enter image description here

1 个答案:

答案 0 :(得分:0)

我想到的一个解决方案涉及子查询和row_number分析函数:

select
  column1,
  max(case when rn = 1 then column2 end) as column2,
  max(case when rn = 2 then column2 end) as column3
from (
  select *, row_number() over (partition by column1 order by column2) as rn
  from table1
  ) t
group by column1

或者您可以像下面这样使用minmax规则,但我更喜欢第一个:

select
  column1,
  min(column2) as column2,
  max(column2) as column3
from table1
group by column1