有条件的COUNT和GROUP BY?

时间:2019-05-15 01:05:18

标签: sql sql-server

我有下表:

CREATE TABLE Source_Table
    ([Student_ID] varchar(10), [Class_ID] varchar(10), [Sport] varchar(10))
;

INSERT INTO Source_Table
    ([Student_ID], [Class_ID], [Sport])
VALUES
    ('S00001', 'C0123A', 'Football'),
    ('S00002', 'C0123A', 'Football'),
    ('S00003', 'C0123A', 'Football'),
    ('S00004', 'C0123A', 'Football'),
    ('S00005', 'C0111B', 'Basketball'),
    ('S00006', 'C0111B', 'Basketball'),
    ('S00007', 'C0211C', 'Basketball'),
    ('S00008', 'C0100D', 'Soccer'),
    ('S00009', 'C0100D', 'Soccer');

,我想要以下输出:

规则是:对于具有count(Student_ID)> = 3的Class_ID,仅计数一次

Sport   Count
Basketball  3
Football    **1**
Soccer  2

我尝试了GROUP BY Sport和COUNT(CLASS_ID),但不确定如何执行该规则。

http://www.sqlfiddle.com/#!18/3e6a3/3

select Sport, Count(Class_Id) from Source_Table
group by Sport

我尝试过的输出是:

Sport   Count
Basketball  3
Football    **4** when I would like it to be Football **1**
Soccer  2

2 个答案:

答案 0 :(得分:2)

您可以通过此查询获得所需的结果。它使用子查询为每种Sport / Class_Id组合计算学生人数。在外部查询中,它对计数进行求和,将具有3个或更多学生的班级的计数替换为1:

select Sport, SUM(CASE WHEN Count >= 3 THEN 1 ELSE Count END) AS Count
FROM (select Sport, Class_Id, Count(Student_Id) AS Count
      from Source_Table
      group by Sport, Class_Id) s
GROUP BY Sport

输出:

Sport       Count
Basketball  3
Football    1
Soccer      2

Updated SQLFiddle

答案 1 :(得分:0)

我认为最简单的方法是case表达式:

select Sport,
       (case when count(*) > 3 then 1 else count(*) end) as cnt
from Source_Table
group by Sport;

如果您需要计算不同的学生,则可以这样做:

select Sport,
       (case when count(distinct class_id) > 3 then 1 else count(*) end) as cnt
from Source_Table
group by Sport;