postgresql 我怎样才能透视一个表,使行变成列?

kx1ctssn  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(2)|浏览(156)

我有一个这样的表,名为people
| 名字|ID|总|类型|
| --|--|--|--|
| 乔| 1234 | 13 |现场|
| 乔| 1234 | 9 |远程|
| 简| 4321 | 99 |远程|
| 简| 4321 | 1 |现场|
我想查询它,并返回如下结果:
| 名字|ID|现场|远程|
| --|--|--|--|
| 乔| 1234 | 13 | 9 |
| 简| 4321 | 1 | 99 |
我相信我需要使用Pivot(),但这对我来说是高级的
谢谢你
我尝试按first_name分组,但这不会将行移动到列

nr9pn0ug

nr9pn0ug1#

使用聚合filter子句。Demo at db<>fiddle:

select first_name,
       id, 
       sum(total)filter(where type='onsite') as onsite,
       sum(total)filter(where type='remote') as remote
from test
group by first_name,
         id;

字符串
| 名字|ID|现场|远程|
| --|--|--|--|
| 乔| 1234 | 13 | 9 |
| 简| 4321 | 1 | 99 |
查看crosstab()

create extension tablefunc;

select * from crosstab(
   $a$ select first_name, id, type, total from people order by 1,2,3 $a$ , 
   $b$ select distinct type from people order by 1 $b$
  ) AS ct(first_name text, id int, onsite int, remote int);

t5zmwmid

t5zmwmid2#

下面是conditional aggregation方法,它很容易理解,如果你只有几个不同的“类型”,IMO推荐使用。

select 
 first_name, 
 id, 
 max(case when type = 'onsite' then total end) as onsite, 
 max(case when type = 'remote' then total end) as remote
from people
group by first_name, id

字符串

相关问题