gpt4 book ai didi

MySQL - 对记录分组执行检查

转载 作者:行者123 更新时间:2023-11-29 06:48:04 24 4
gpt4 key购买 nike

我有这样的结果集:

"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) 执行检查。

最佳答案

(更新)尝试:

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 .

关于MySQL - 对记录分组执行检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17389226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com