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: Case with conditions based on two columns

Imagine the dummy data

id   name     category    score   
1    Alex     A           11        
2    Alex     D           4      
3    Bill     A           81     
4    Bill     B           34       
5    Bill     D           2       
6    Carl     C           5       
7    Carl     D           10       

I would like to apply the action:

if score of A, B, or C > score of D
then 'Review'
else 'Pass'

So the output is:

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

id   name     category    score   conclusion
1    Alex     A           11       Review
2    Alex     D           4        Review
3    Bill     A           81       Review
4    Bill     B           34       Review
5    Bill     D           2        Review
6    Carl     C           5        Pass
7    Carl     D           10       Pass

how can I obtain this in PostgreSQL?

>Solution :

You want conditional aggregation with window functions:

select
  id, name, category, score,
  case when 
         max(score) filter (where category in ('A', 'B', 'C')) over (partition by name) >
         min(score) filter (where category = 'D')              over (partition by name)
       then 'Review'
       else 'Pass'
  end as result
from mytable
order by name, id;

If there is no A, B or C for a name or no D for a name, the result will be ‘Pass’. If you want this differently, then you’ll have to adjust the camparison.

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