如果我有一个如下表,我该如何计数和汇总所有不同的值?
student_name | section | score | class
-------------|---------|-------|-------
John | B | 32 | 8
Doe | B | 43 | 8
Jane | A | 33 | 8
Smith | A | 88 | 8
Pat | B | 99 | 9
每个班级我都希望得到以下输出。因此,对于类8
,它将是:
section | num_records | score_total
---------|--------------|-------------
B | 2 | 75
A | 2 | 121
Total | 4 | 196
答案 0 :(得分:2)
您可以使用GROUPING SETS
:
SELECT COALESCE(section, 'Total') AS section,
COUNT(*) AS num_records,
SUM(score) AS score_total
FROM t
WHERE class = 8
GROUP BY GROUPING SETS (section, ())
ORDER BY section;
答案 1 :(得分:0)
您可以使用全部合并和子查询
select section,count(*),sum(score)
from t
where class =8
group by section
union all
select 'Total',count(*),sum(score) from t
where class=8
demo 输出
section count sum
A 2 121
B 2 75
Total 4 196