MySQl使用COUNT和CASE语句

时间:2018-07-22 06:55:22

标签: mysql sql

在我的mysql数据库中,我有instagram_actions_histories表,其中有两个重要列分别为action_typeaction_name,现在我想使用count和case语句获取id的计数s列,例如:

id等于action_type并且1等于“喜欢”时,所有action_name的数量

select `account_id`,

count(case when action_type = 1 and action_name='like' then id else 0 END) as `like`,
count(case when action_type = 1 and action_name='superLike' then id else 0 END) as `superLike`,
count(case when action_type = 2 then id else 0 END) as `follow`, 

from `instagram_actions_histories` 
where `instagram_actions_histories`.`account_id` in (1) 
group by `account_id`

不幸的是,由于所有输出都相同,因此我得到了错误的结果,例如:

account_id  like    superLike    follow
1           1282    1282         1282

正确的结果应该是:

account_id  like    superLike    follow
1           1282    20           10

1 个答案:

答案 0 :(得分:4)

您应该为一场比赛计数1,如果没有一场比赛,则计数NULL

SELECT
    account_id,
    COUNT(CASE WHEN action_type = 1 AND action_name = 'like' THEN 1 END) AS `like`,
    COUNT(CASE WHEN action_type = 1 AND action_name = 'superLike' THEN 1 END) AS superLike,
    COUNT(CASE WHEN action_type = 2 THEN 1 END) AS follow
FROM instagram_actions_histories
WHERE account_id IN (1)
GROUP BY account_id;

CASE表达式的当前逻辑存在的问题是COUNT会将任何非null值都计为一个计数。因此零也将被计数。

请注意,您当前的逻辑使用SUM进行条件聚合,例如

SUM(CASE WHEN action_type = 1 AND action_name = 'like'
         THEN 1 ELSE 0 END) AS `like`

在这种情况下,要关闭不匹配记录的汇总,实际上我们可以使用零,因为将零相加不会影响总和。