MySQL - 对记录分组执行检查

时间:2013-06-30 10:05:09

标签: mysql sql stored-procedures

我有这样的结果集:

"id","reference_id","type"
"1","aaa","A"
"2","aab","M"
"3","aac","A"
"4","aaa","M"
"5","aaa","E"
"6","aab","M"
"7","aac","M"
"8","aab","D"
"9","aac","M"

我想使用sql对它运行一些验证。

  • 每个reference_id生命周期必须只包含一个“A”;
  • 每个reference_id生命周期必须至少包含1“E”和/或1“D”;

如何遍历结果集并对每组记录执行检查(reference_id)。

1 个答案:

答案 0 :(得分:2)

(更新)尝试:

select r.* 
from my_result_set r
join (select reference_id
      from my_result_set
      group by reference_id
      having sum(case type when 'A' then 1 end) = 1 and
             sum(case when type in ('D','E') then 1 end) >= 1) s
  on r.reference_id = s.reference_id

SQLFiddle here