计数(不同)超过(分区依据)sql 服务器 2016
Count(distinct) over (partition by) sql server 2016
我有一个 table 如下所示
class_no
student_id
subject_name
1
636
Physics
1
636
Chemistry
1
637
Maths
1
638
German
1
639
Physics
Create table #T_Test(
class_no int
,student_id int
,subject_name nvarchar(25)
);
Insert into #T_Test ([class_no],[student_id],[subject_name]) values
(1,636,'Physics'),
(1,636,'Chemistry'),
(1,637,'Maths'),
(1,638,'German'),
(1,639,'Physics')
我想得到不同 student_id 的计数,还要计算 grouped_by subject_names
class_no
subject_name
total_subjects
total_students
1
Physics
2
4
1
Chemistry
1
4
1
Maths
1
4
1
German
1
4
1
Physics
1
4
下面是我到目前为止所做的,我怎样才能得到结果集中包含的非重复计数(student_id)
SELECT DISTINCT t.class_no
,t.subject_name
,count(*) total_subject
FROM #T_Test t
WHERE t.class_no = 1
GROUP BY t.class_no,subject_name
我认为您正在寻找这个查询:
SELECT DISTINCT
t.class_no,
t.subject_name,
total_subjects = Count(t.subject_name) OVER(Partition By t.class_no, t.subject_name),
total_students = (SELECT COUNT(Distinct [student_id]) FROM #T_Test)
FROM #T_Test t
WHERE t.class_no = 1
通过使用这个 dense_rank
小技巧,无需多次点击 table 即可获得科目总数和不同的学生人数:
with s as (
select class_no, subject_name,
Dense_Rank() over (partition by class_no order by student_id) +
Dense_rank() over (partition by class_no order by student_id desc) - 1 Students
from #T_Test
)
select class_no, subject_name,
Count(*) Total_Subjects,
Max(students) Total_Students
from s
group by class_no, subject_name
我有一个 table 如下所示
class_no | student_id | subject_name |
---|---|---|
1 | 636 | Physics |
1 | 636 | Chemistry |
1 | 637 | Maths |
1 | 638 | German |
1 | 639 | Physics |
Create table #T_Test(
class_no int
,student_id int
,subject_name nvarchar(25)
);
Insert into #T_Test ([class_no],[student_id],[subject_name]) values
(1,636,'Physics'),
(1,636,'Chemistry'),
(1,637,'Maths'),
(1,638,'German'),
(1,639,'Physics')
我想得到不同 student_id 的计数,还要计算 grouped_by subject_names
class_no | subject_name | total_subjects | total_students |
---|---|---|---|
1 | Physics | 2 | 4 |
1 | Chemistry | 1 | 4 |
1 | Maths | 1 | 4 |
1 | German | 1 | 4 |
1 | Physics | 1 | 4 |
下面是我到目前为止所做的,我怎样才能得到结果集中包含的非重复计数(student_id)
SELECT DISTINCT t.class_no
,t.subject_name
,count(*) total_subject
FROM #T_Test t
WHERE t.class_no = 1
GROUP BY t.class_no,subject_name
我认为您正在寻找这个查询:
SELECT DISTINCT
t.class_no,
t.subject_name,
total_subjects = Count(t.subject_name) OVER(Partition By t.class_no, t.subject_name),
total_students = (SELECT COUNT(Distinct [student_id]) FROM #T_Test)
FROM #T_Test t
WHERE t.class_no = 1
通过使用这个 dense_rank
小技巧,无需多次点击 table 即可获得科目总数和不同的学生人数:
with s as (
select class_no, subject_name,
Dense_Rank() over (partition by class_no order by student_id) +
Dense_rank() over (partition by class_no order by student_id desc) - 1 Students
from #T_Test
)
select class_no, subject_name,
Count(*) Total_Subjects,
Max(students) Total_Students
from s
group by class_no, subject_name