简体   繁体   English

Postgres 中的交叉表/数据透视表 SQL

[英]Crosstab/Pivot in Postgres SQL

I need to convert rows to columns in PostgreSql. It would be great if someone can put some shed on this.我需要将 PostgreSql 中的行转换为列。如果有人可以对此进行一些处理,那就太好了。 I tried to solve this using crosstab but no luck.我尝试使用交叉表解决此问题,但没有成功。

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
) 

Attached Screenshot of the data.附上数据截图。 数据集

I prefer filtered aggregation, as I find that to be easier to maintain and understand:我更喜欢过滤聚合,因为我发现它更容易维护和理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM