我有以下8条记录:
ID | Common ID | Reject
-------------------------
AB-1 | AB | NULL
AB-2 | AB | YES
AB-3 | AB | NULL
BB-1 | BB | YES
BB-2 | BB | YES
BB-3 | BB | YES
CB-1 | CB | YES
CB-2 | CB | YES
DB-1 | DB | NULL
我的预期结果是:
ID | Common ID | Reject
-------------------------
BB-1 | BB | YES
CB-1 | CB | YES
当所有具有相同公共ID的记录的拒绝列为yes时,我只想获取不同的记录。
select min(ID), [Common ID], max(Reject)
from tablename
group by [Common ID]
having count(*) = count(case when Reject = 'YES' then 1 end)
如果[公共ID]的行数与YES的行数相同,则将其返回!
该HAVING
条款的count(*)
返回行的总数[Common ID]
。该case
表达式返回1,如果拒绝=是,否则返回null。右边count
返回行数,如果大小写返回非空值(即,当Reject为yes时)。如果行数相同,HAVING
则为true!
编辑:
在这种特定情况下,当“拒绝”列的值似乎为YES或NULL时,HAVING
可以简化为:
having count(*) = count(Reject)
但是,如果以后会在该列中找到其他值(例如NO),则此方法将无效。因此,我建议使用原始HAVING
条款!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句