Eliminate records by grouping and aggregation
P粉731861241
P粉731861241 2023-08-17 19:20:03
0
1
328
<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粉731861241
P粉731861241

reply all(1)
P粉245003607

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template