如何在1个查询中使用COUNT()和SUM()

时间:2014-03-14 14:38:55

标签: mysql sql

我正在努力获得学生成绩和学生人数

表架构

Stud_ID|Stud_Name|Marks|Class
1      | A       |20   |1   
1      | A       |10   |1
1      | A       |22   |1
5      | G       |21   |1
5      | G       |16   |1
5      | G       |27   |1
2      | B       |13   |1
2      | B       |14   |1
2      | B       |21   |1
2      | B       |13   |1
2      | B       |21   |1
3      | C       |10   |1
3      | C       |17   |1
3      | C       |16   |1

我需要每个学生的总分数以及表中有多少学生。我正在尝试将DISTINCT和SUM结合起来但不起作用

SELECT count(
sum(`mark`) FROM `es_marks_entry_summery` where `class` ='16' group by `Stud_ID`)

4 个答案:

答案 0 :(得分:0)

select *
from (
    select stud_id, sum(mark) as mark
    from es_marks_entry_summery
    where class = '16'
    group by stud_id
) t1, (
    select count(distinct stud_id) as student_count
    from es_marks_entry_summery
    where class = '16'
) t2

答案 1 :(得分:0)

DECLARE @Result TABLE (Stud_ID INT, Marks INT)

INSERT INTO @Result(Stud_ID, Marks) SELECT COUNT(Stud_ID), SUM(Marks) from es_marks_entry_summery WHERE Class = '16'

SELECT * FROM @Result

答案 2 :(得分:0)

这就是你想要的

SELECT 
    id, 
    name, 
    SUM(marks) as total_marks, 
    (select count(distinct id) FROM t WHERE class = 16) as num_students
FROM t
GROUP BY id

请在此处查看示例小提琴:http://sqlfiddle.com/#!2/4baed/4

然后您可以按类过滤,或者您需要使用WHERE子句

对其进行自定义

如果您还希望它是每个班级中有标记的学生的唯一数量,那么只需将GROUP BY更改为此

GROUP BY id, class

答案 3 :(得分:0)

  select *  from (select class ,Stud_ID, sum(Marks) as Marks from tbl  group by Stud_ID) tbl1, (select count(distinct Stud_ID) as Times from tbl) tbl2
    where Class=16;

请参阅小提琴中的示例:http://sqlfiddle.com/#!8/10701