Home > database >  Postgresql how to group the values in on column of a table and transpose the unique values of anothe
Postgresql how to group the values in on column of a table and transpose the unique values of anothe

Time:02-13

I am new to SQL in general, hence this problem is a little tricky to me. I have a table like the example below:

Input Values:

enter image description here

And, I wish to get the following output:

Output Result:

enter image description here

Honestly, I have no idea how to begin to solve this problem. I would appreciate a hint and/or an example solution from anyone. Thank you in advance.

CodePudding user response:

You can perform conditional aggregation and then use a ROLLUP.

For example:

select
  velocity,
  sum(case when volume = 'VERY HIGH' then sales else 0 end) as very_high,
  sum(case when volume = 'HIGH' then sales else 0 end) as high,
  sum(case when volume = 'MEDIUM-HIGH' then sales else 0 end) as medium_high,
  sum(case when volume = 'LOW' then sales else 0 end) as low,
  sum(case when volume = 'VERY LOW' then sales else 0 end) as very_low,
  sum(sales) as total
from t
group by rollup (velocity)
order by velocity
  • Related