组计数和总计数的SQL语句

时间:2013-01-16 08:10:13

标签: sql oracle

给出以下测试数据:

╔═════════╦══════╦═══════╗
║ STUDENT ║ TEST ║ SCORE ║
╠═════════╬══════╬═══════╣
║ Henry   ║    1 ║    80 ║
║ Henry   ║    2 ║    70 ║
║ Henry   ║    3 ║    50 ║
║ Mark    ║    1 ║    60 ║
║ Mark    ║    2 ║    90 ║
║ Mark    ║    3 ║    70 ║
║ Frank   ║    1 ║    80 ║
║ Frank   ║    2 ║    70 ║
║ Frank   ║    3 ║    80 ║
╚═════════╩══════╩═══════╝ 

现在我很有兴趣看到每个学生得分80分以及80分的总数是80分。这样的事情:

╔═════════╦════════════╦══════════════╗
║ STUDENT ║ OWN_80_CNT ║ TOTAL_80_CNT ║
╠═════════╬════════════╬══════════════╣
║ Frank   ║          2 ║            3 ║
║ Mark    ║          0 ║            3 ║
║ Henry   ║          1 ║            3 ║
╚═════════╩════════════╩══════════════╝

到目前为止我所拥有的是own_80_cnt。但我不知道如何在它旁边添加total_80_cnt。

SELECT  student,
        SUM(CASE WHEN score = 80 THEN 1 ELSE 0 END) AS own_80_cnt
FROM    mytable 
GROUP BY student;

这是否只能在一个SELECT语句中使用(首选)? DBMS是Oracle。

2 个答案:

答案 0 :(得分:0)

添加一个内联子查询,分别获得等于80的分数。

SELECT  student,
        SUM(CASE WHEN score = 80 THEN 1 ELSE 0 END) AS own_80_cnt,
        (SELECT COUNT(*) FROM myTable WHERE score = 80) AS total_80_cnt
FROM    mytable 
GROUP BY student;

答案 1 :(得分:0)

你可以用分析来做到这一点:

select student, own_80_cnt,
       sum(own_80_cnt) over () total_80_cnt
  from (select student,
               sum(case when score = 80 then 1 else 0 end) as own_80_cnt
          from mytable
         group by student);