Skip to content
Advertisement

pivot table with multiple value columns in postgres

I need a query which will help me to get data as described below

I have a table as followed

ID date STATUS TIME09_10 TIME10_11 TIME11_12 TIME12_13
1 2021-09-01 RUN 30 60 45 0
2 2021-09-01 WALK 15 0 o 30
3 2021-09-01 STOP 15 0 15 30

I want this data to be in below format. From the above table , value columns name has to be replaced with hour and join with date column. I would really appreciate someone’s help. I am using postgres sql database.

date & time run walk stop
2021-09-01 09:00 30 15 15
2021-09-01 10:00 60 0 0
2021-09-01 11:00 45 0 15
2021-09-01 12:00 0 30 30

Advertisement

Answer

You can use the crosstab(source_sql text, category_sql text) function. You need to install the tablefunc extension:

Read about the extension in the documentation.

The function expects data in the three-column format (row_name, category, value). In this case they are date+time, status and duration.

Pass the query as the first argument to the function:

There is a nice alternative if you do not want to use the extension. Convert the first query results to the expected output with the jsonb function:

Test the jsonb solution in Db<>fiddle.

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