I need to convert rows to columns in PostgreSql. It would be great if someone can put some shed on this. 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
)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.