在我的mysql数据库中,我有instagram_actions_histories
表,其中有两个重要列分别为action_type
和action_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
答案 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`
在这种情况下,要关闭不匹配记录的汇总,实际上我们可以使用零,因为将零相加不会影响总和。