Skip to content
Advertisement

How to pivot in postgresql

I have table like following,and I would like to transform them.

I’d like to pivot like following.

I tried like following statement, but it returned a lot of null columns. And I wonder I must add columns one by one when new type will be added.

If someone has opinion, please let me know. Thanks

Advertisement

Answer

demo: db<>fiddle

You can either use the FILTER clause:

or you can use the CASE clause:

  1. In both cases you need to perform a GROUP BY action.
  2. This makes an aggregation function necessary, like MAX() or SUM(). Finally you need to apply a kind of filter (CASE or FILTER) to only aggregate the related data.

Additionally: Please note that the words count, year, month, week are keywords of SQL. To avoid any complications you should think about other column names.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement