CROSSTAB and PIVOT

Viewed 24

I have the following table -

org_id  et  rt         level     diagnosis   count
9453    2   AGENCY     SERVICE   MMTA    18
9453    1   PHYSICIAN  SERVICE   M_WOUND     5
9453    1   REFERRER   SERVICE   M_WOUND 5
9453    1   REFERRER   SERVICE   N_WOUND 5

How do I pivot this table such that -

org_id  et  rt         level     MMTA  M_WOUND   N_WOUND
9453    2   AGENCY     SERVICE   18   
9453    1   PHYSICIAN  SERVICE         5
9453    1   REFERRER   SERVICE   0     5         5
1 Answers

You can use conditional aggregation:

select org_id, et, rt, level,
       max(count) filter (where diagnosis = 'MMTA') as mmta,
       max(count) filter (where diagnosis = 'M_WOUND') as m_wound,
       max(count) filter (where diagnosis = 'N_WOUND') as n_wound
from t
group by org_id, et, rt, level;
Related