Eliminate records by grouping and aggregation
P粉731861241
2023-08-17 19:20:03
<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>
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 ofpassed
in each group.1
if all values aretrue
, or0
if anyfalse
values are present.