Reputation: 189
I am trying and failing to write a script to return any unique combinations of job and suffix where the (oper = 20 and value = 0) and (oper > 20 and value = 1). Based on the data below there is only one instance, job 2 suffix 3. In this combination of job and suffix the oper 20 = 0 and the oper 40 = 1.
job suffix oper value
1 1 20 0
1 1 30 0
2 3 20 0
2 3 40 1
3 2 20 0
3 3 50 1
Any help would be appreciated
Upvotes: 0
Views: 56
Reputation: 44581
SELECT job
, suffix
FROM t1
GROUP BY job
, suffix
HAVING COUNT(CASE WHEN (oper = 20 and value = 0) OR (oper > 20 and value = 1) THEN suffix END) = COUNT(*)
AND COUNT(*) = 2
Upvotes: 1
Reputation: 1269443
One way to approach this is as a "set-within-sets" subquery. A flexible approach to solving these is using group by
and having
. In your case:
select t.job, t.suffix
from table t
group by t.job, t.suffix
having sum(case when oper = 20 and value = 0 then 1 else 0 end) > 0 and
sum(case when oper > 20 and value = 1 then 1 else 0 end) > 0;
Each condition in the having
clause counts the number of rows that match a specific condition. So, the first ensure that there is at least one row where oper = 20 and value = 0
.
Upvotes: 1