1

我正在尝试在存储过程中生成一些用户分析。

这是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 语句中获取三个级别的单独计数和总和值,而不是像上面那样单独的 sql 语句。

4

3 回答 3

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 
于 2013-10-15T06:29:07.770 回答
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;
于 2013-10-15T06:29:28.167 回答
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 中的布尔值是1or 0

于 2013-10-15T06:31:41.847 回答