我正在尝试在存储过程中生成一些用户分析。
这是sql代码:
SELECT count(*),SUM(n.credit) from notifications n
left join questions q on q.id = n.question_id
where n.user_id = u_id and q.question_level = 1 ;
列q.question_level
有三个可能的值=> 1,2 and 3
有没有办法在单个sql语句中获取三个级别的单独count和sum值,而不是如上所述的单独的sql语句。
答案 0 :(得分:1)
你的意思是这样吗?
SELECT
count(*),
SUM(n.credit) AS totalCredit,
SUM(CASE WHEN q.question_level = 1 THEN n.credit ELSE 0 END) as level1_sum,
SUM(CASE WHEN q.question_level = 2 THEN n.credit ELSE 0 END) as level2_sum,
SUM(CASE WHEN q.question_level = 3 THEN n.credit ELSE 0 END) as level3_sum,
SUM(q.question_level = 1) as level1_count,
SUM(q.question_level = 2) as level2_count,
SUM(q.question_level = 3) as level3_count
from
notifications n
left join questions q
on q.id = n.question_id
where
n.user_id = u_id
答案 1 :(得分:1)
试试这个:
SELECT COUNT(*), SUM(n.credit)
FROM notifications n LEFT JOIN questions q ON q.id = n.question_id
WHERE n.user_id = u_id
GROUP BY q.question_level;
答案 2 :(得分:1)
像这样:
SELECT
count(*) total_count,
SUM(n.credit) total_credit,
SUM(q.question_level = 1) as level1_count,
SUM(q.question_level = 2) as level2_count,
SUM(q.question_level = 3) as level3_count,
SUM(n.credit * (q.question_level = 1)) as level1_credit,
SUM(n.credit * (q.question_level = 2)) as level2_credit,
SUM(n.credit * (q.question_level = 3)) as level3_credit
from notifications n
left join questions q on q.id = n.question_id
where n.user_id = u_id
方便地,mysql中的布尔值为1
或0
。