Andres Clavijo Andres Clavijo - 4 months ago 11
SQL Question

Reorganize Postgrest Query

Im using a query on postgresql that return a result like this.

schedule | day | subject | grade |
===============================================
06 - 08 | Monday | Biology | Second |
-----------------------------------------------
08 - 10 | Monday | Chemistry | Third |
-----------------------------------------------
06 - 08 | Tuesday | Math | Second |
-----------------------------------------------
10 - 12 | Wednesday | English | Second |
-----------------------------------------------
10 - 12 | Friday | Language | Second |
-----------------------------------------------


I need a result or reorganize this query like this.

schedule | Monday | Tuesday| Wednesday | Friday | grade
==============================================================
06 - 08 | Biology | Math | null | null | second
--------------------------------------------------------------
10 - 12 | null | null | English |Language | second
--------------------------------------------------------------


I appreciate any help or suggestion.

Thnks.

Answer

One method is conditional aggregation:

select schedule,
       max(case when day = 'Monday' then subject end) as Monday,
       max(case when day = 'Tuesday' then subject end) as Tuesday,
       max(case when day = 'Wednesday' then subject end) as Wednesday,
       max(case when day = 'Friday' then subject end) as Friday,
       min(grade) as grade,
from t
group by schedule;

I'm not really sure where the grade comes from; the above is just a guess.

Comments