COUNT WHERE 在同一列中同时满足两个条件
Posted
技术标签:
【中文标题】COUNT WHERE 在同一列中同时满足两个条件【英文标题】:COUNT WHERE two conditions are met in the same column 【发布时间】:2020-11-08 18:24:48 【问题描述】:我确定以前有人问过这个问题,但我找不到类似的情况:
给定一张桌子'activity'
user_ID | contact_channel_ID
123456 email
123456 email
555555 SEM
555555 SEM
995959 phone
995959 SEM
696969 email
696969 email
我需要统计在contact_channel_ID
中拥有“SEM”和至少另一个频道的所有用户
【问题讨论】:
【参考方案1】:你可以使用聚合和having
:
select user_id
from activity
group by user_id
having sum(case when contact_channel_ID = 'SEM' then 1 else 0 end) > 0 and
sum(case when contact_channel_ID <> 'SEM' then 1 else 0 end) > 0;
在 mysql 中,having
子句可以简写为:
having sum(contact_channel_ID = 'SEM') > 0 and
sum(contact_channel_ID <> 'SEM') > 0;
【讨论】:
【参考方案2】:你可以使用聚合:
select user_id
from activity
group by user_id
having max(contact_channel_id = 'SEM') = 1
and max(contact_channel_id <> 'SEM') = 1
如果要统计此类用户,则添加另一个级别的聚合:
select count(*) as cnt
from (
select 1
from activity
group by user_id
having max(contact_channel_id = 'SEM') = 1
and max(contact_channel_id <> 'SEM') = 1
) t
【讨论】:
【参考方案3】:按用户分组并在HAVING子句中设置条件:
SELECT user_id
FROM activity
GROUP BY user_id
HAVING COUNT(DISTINCT contact_channel_id) > 1
AND SUM(contact_channel_id = 'SEM') > 0
或与 EXISTS:
SELECT DISTINCT a.user_id
FROM activity a
WHERE a.contact_channel_id = 'SEM'
AND EXISTS (SELECT 1 FROM activity WHERE user_id = a.user_id AND contact_channel_id <> a.contact_channel_id)
如果您想统计用户数,请将上述查询更改为:
SELECT COUNT(DISTINCT a.user_id) counter
FROM activity a
WHERE a.contact_channel_id = 'SEM'
AND EXISTS (SELECT 1 FROM activity WHERE user_id = a.user_id AND contact_channel_id <> a.contact_channel_id)
请参阅demo。 结果:
> | user_id |
> | ------: |
> | 995959 |
和:
> | counter |
> | ------: |
> | 1 |
【讨论】:
以上是关于COUNT WHERE 在同一列中同时满足两个条件的主要内容,如果未能解决你的问题,请参考以下文章