簡體   English   中英

Postgres 中的交叉表/數據透視表 SQL

[英]Crosstab/Pivot in Postgres SQL

我需要將 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
) 

附上數據截圖。 數據集

我更喜歡過濾聚合,因為我發現它更容易維護和理解:

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