Home  >  Q&A  >  body text

Eliminate records by grouping and aggregation

<p>I have a temporary table with the following content: </p> <pre class="brush:php;toolbar:false;">playlist_id | item_id | passed ---------------------------------------- 123 | 111 | true 123 | 111 | false 123 | 111 | true 123 | 112 | true 456 | 212 | false 789 | 212 | true</pre> <p>I need to reduce the results, if for a <code>playlist_id, item_id</code>, I need to keep it only if all the <code>passed</code> values ​​are true, so in In this example, the result I want is: </p> <pre class="brush:php;toolbar:false;">playlist_id | item_id | passed ---------------------------------------- 123 | 112 | true 789 | 212 | true</pre> <p>Because the second record's <code>playlist_id, item_id</code> pair has a <code>false</code> value, the entire corresponding group needs to be deleted. I tried using <code>group by</code> and <code>having</code>, so the query is: </p> <pre class="brush:php;toolbar:false;">select playlist, item_id from temp table group by playlist_id, item_id having passed = true</pre> <p>But this returns me all pairs that have at least one <code>true</code> value. </p> <p>How do I eliminate all <code>playlist_id, item_id</code> records if any of the boolean <code>passed</code> fields is false? </p> <p>Thank you! </p>
P粉731861241P粉731861241429 days ago309

reply all(1)I'll reply

  • P粉245003607

    P粉2450036072023-08-18 10:37:55

    You need to use aggregate values ​​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. 1 if all values ​​are true, or 0 if any false values ​​are present.

    SELECT playlist, item_id
    FROM temp_table
    GROUP BY playlist, item_id
    HAVING MIN(passed) = true

    reply
    0
  • Cancelreply