Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgresql Group By and create columns for different values

I’m using Postgresql and have this table:

device_id date variable_name pulses
1 2021-03-29 height 10
1 2021-03-29 speed 20
1 2021-03-30 height 30
1 2021-03-30 temperature 40
2 2021-03-29 height 50
2 2021-03-29 acceleration 60
2 2021-03-29 distance 70

And want to query so I Group By device_id and date, and create columns by variable_name, so the table expected is:

device_id date height speed temperature acceleration distance
1 2021-03-29 10 20 0 0 0
1 2021-03-30 30 0 40 0 0
2 2021-03-29 50 0 0 60 70

Any idea of how to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

in addition to crosstab, there is a more direct way through case operator

Select device_id, date, 
       Sum(Case When variable_name='height' Then pulses Else 0 End) As height,
       Sum(Case When variable_name='speed' Then pulses Else 0 End) As speed,
       Sum(Case When variable_name='temperature' Then pulses Else 0 End) As temperature,
       Sum(Case When variable_name='acceleration' Then pulses Else 0 End) As acceleration,
       Sum(Case When variable_name='distance' Then pulses Else 0 End) As distance
From Tbl
Group by device_id, date
Order by device_id, date

Data Output:

device_id| date                 | height | speed | temperature | acceleration | distance
_________|______________________|________|_______|_____________|______________|_________
        1| 2021-03-29 00:00:00  |      10|     20|            0|             0|        0
        1| 2021-03-30 00:00:00  |      30|      0|           40|             0|        0
        2| 2021-03-29 00:00:00  |      50|      0|            0|            60|       70
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading