计算SQL中的出现次数

时间:2019-07-02 17:36:43

标签: sql

我具有以下表格结构:

Student   School Code   Roll Number
A           12            135
B           12            248
C           16            934
D           16            437
E           12            249

我想通过一个学校代码获取学生人数并显示该人数。我可以执行row_number并以这种方式获取行数:

select student, School code, 
row_number() over(partition by School Code order by Roll Number) AS line_no
from table ;

输出为:

Student   School Code   line_no   Total_Count
A            12           1          3
B            12           2          3
E            12           3          3
D            16           1          2
C            16           2          2

我无法编写sql代码以产生最后一列(即Total_Count)。 你能告诉我怎么做吗?

1 个答案:

答案 0 :(得分:1)

您需要count()窗口功能:

select student, School code, 
       row_number() over(partition by School Code order by Roll Number) as line_no
       count(*) over(partition by School Code) as total_count
from table ;