巧用having解决统计问题

有一张学员考试分数表结构如下:

create table ScoreTB
(
    Id int identity(1,1) primary key,
    UserId int, --学员编号
    Course int, --科目
    Score int --分数
)

给表中添加一些测试数据:

insert into ScoreTB(UserId,Course,Score) select 1,1,80
union all select 2,1,90
union all select 2,2,80
union all select 2,3,50
union all select 3,1,100
union all select 3,2,95
union all select 3,3,89

①.统计已经参加过科目一、科目二和科目三考试的学员:

select UserId from ScoreTB where Course in (1,2,3) group by UserId having count(*)=3

引用内容 引用内容
UserId      
-----------
2
3

(所影响的行数为 2 行)

②.统计过了三个科目的学员:

select UserId from ScoreTB where Course in (1,2,3) and Score>=60 group by UserId having count(*)=3

引用内容 引用内容
UserId      
-----------
3

(所影响的行数为 1 行)


评论: 0 | 引用: 0 | 查看次数: 3167
发表评论
登录后再发表评论!