count()函数里面想实现带条件统计,可以使用SUM函数来进行替换,具体可以使用case when 语句或者Decode函数来对要统计的数据进行0、1转换,
如下例子:
SELECT s.user_id,SUM(case(m.is_success) when 1 then 1 else 0 end),SUM(case when m.read_time IS NULL then 0 else 1 end),COUNT(*)
from doc_score s,mail_send_log m where s.user_id in(6,7,8,9) and s.status = 1 and m.doc_id = s.doc_id
group by s.user_id
;
如下例子:
SELECT s.user_id,SUM(case(m.is_success) when 1 then 1 else 0 end),SUM(case when m.read_time IS NULL then 0 else 1 end),COUNT(*)
from doc_score s,mail_send_log m where s.user_id in(6,7,8,9) and s.status = 1 and m.doc_id = s.doc_id
group by s.user_id
;

本文介绍了一种在SQL中使用SUM函数结合CASE WHEN语句进行条件计数的方法,通过将符合条件的数据转换为1,不符合条件的数据转换为0,进而实现对特定条件的数据行数进行统计。这种方法特别适用于需要按不同条件分别统计数量的场景。
7422

被折叠的 条评论
为什么被折叠?



