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

Group-by and having aggregates to eliminate records

I have a temporary table like this.

playlist_id |   item_id  |    passed
-----------------------------------------
 123        |   111      |    true
 123        |   111      |    false
 123        |   111      |    true
 123        |   112      |    true
 456        |   212      |    false
 789        |   212      |    true

I need to reduce the results so that if for a playlist_id, item_id if and only if all of the values in passed are true, so in this case I’d want:

playlist_id |   item_id  |    passed
-----------------------------------------
 123        |   112      |    true
 789        |   212      |    true

Because the second record has a false for the playlist_id, item_id pair, the entire pairing group needs to be eliminated.
I’ve tried using group by and having, so

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

select 
  playlist, 
  item_id
from 
  temp table
group by
  playlist_id,
  item_id
having passed = true

But it is giving me all pairs that have at least a single true value.

How do I eliminate all playlist_id, item_id records if any one of its boolean passed fields is false?

Cheers!

>Solution :

You need to use an aggregated value in HAVING. Otherwise, you’re just testing a random row in each group.

Use MIN(passed) to get the minimum value of passed in each group. This will be 1 if all the values are true, 0 if there are any false values.

SELECT playlist, item_id
FROM temp_table
GROUP BY playlist, item_id
HAVING MIN(passed) = true
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