postgresql Postgres SQL中的交叉表/透视表

6bc51xsx  于 2022-11-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(127)

我需要在PostgreSQL中将行转换为列。如果有人能在这上面放一些棚就太好了。我试着用交叉表解决这个问题,但没有运气。

select *
from crosstab(
    'select
    count(distinct no_of_cars) as no_of_cars,
    car_type,
    month
from abc
group by 2, 3
order by 3',
    'select distinct month from abc order by month'
) as ct(
    no_of_cars text,
    car_type text,
    month text
)

随附数据截图。

mf98qq94

mf98qq941#

我更喜欢筛选聚合,因为我发现它更容易维护和理解:

select car_model, 
       sum(no_of_cars) filter (where month = 'Nov-22') as "Nov-22",
       sum(no_of_cars) filter (where month = 'Oct-22') as "Oct-22",
       sum(no_of_cars) filter (where month = 'Sep-22') as "Set-22"
from the_table
group by car_model

相关问题