0

给出以下测试数据:

╔═════════╦══════╦═══════╗
║ 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 分。像这样:

╔═════════╦════════════╦══════════════╗
║ 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 是甲骨文。

4

2 回答 2

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;
于 2013-01-16T08:12:05.270 回答
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);
于 2013-01-16T08:21:50.777 回答