gpt4 book ai didi

sql - 分组时选择双条件计数

转载 作者:行者123 更新时间:2023-12-04 20:54:03 24 4
gpt4 key购买 nike

我有一个包含以下相关字段的表格:

entity_id | grouping_id | type_id
---------------------------------
1 | 1 | 1
2 | 1 | 1
3 | 1 | 2
4 | 2 | 1
5 | 2 | 2

我想选择所有 grouping_id 值,其中有 X 个类型 n 和 Y 个类型 m。我最初认为可行的示例:

select grouping_id from t_entities
group by grouping_id, type_id
having
count(case type_id when 1 then 1 else null end) = 2
and
count(case type_id when 2 then 1 else null end) = 1

理论上会返回所有具有 2 个类型 1 和 1 个类型 2 的 grouping_id 值,但是因为该子句也是按 type_id 分组的,所以我什么也得不到,因为每个组都是独立存在的,但是如果我按 type_id 删除组,则会出现聚合错误。有没有办法在不使用临时表的情况下将其作为原始查询执行?

最佳答案

您的查询方向正确,但是您不应该按 type_id 分组,而应该按 grouping_id 分组。通过按 type_id 分组,您永远不会得到具有两个不同值的东西,因此 having 中的 and 子句将不起作用.您应该能够执行以下命令以返回 grouping_id =1 作为结果:

select grouping_id 
from t_entities
group by grouping_id
having count(case type_id when 1 then 1 else null end) = 2
and count(case type_id when 2 then 1 else null end) = 1;

参见 SQL Fiddle with Demo

关于sql - 分组时选择双条件计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34345725/

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