--> 测试数据:#a if object_id('tempdb.dbo.#a') is not null drop table #a create table #a(用户号 varchar(8), 课程号 varchar(8), 选择状态 int) insert into #a select 'U01', 'L01', 1 union all select 'U01', 'L02', 1 union all select 'U01', 'L03', 0 union all select 'U02', 'L01', 1 union all select 'U02', 'L02', 0 --> 测试数据:#b if object_id('tempdb.dbo.#b') is not null drop table #b create table #b(课程号 varchar(8), 课程名称 varchar(8), 课时 int) insert into #b select 'L01', '课程A', 10 union all select 'L02', '课程B', 20 union all select 'L03', '课程C', 30 --> 测试数据:#c if object_id('tempdb.dbo.#c') is not null drop table #c create table #c(用户号 varchar(8), 用户名称 varchar(8), 班级号 varchar(8)) insert into #c select 'U01', '张三', 'C01' union all select 'U02', '李四', 'C02' --> 测试数据:#d if object_id('tempdb.dbo.#d') is not null drop table #d create table #d(班级号 varchar(8), 班级名称 varchar(8)) insert into #d select 'C01', '班级1' union all select 'C02', '班级2'select a.用户号, c.用户名称, d.班级名称, 未审核课时 = sum(case a.选择状态 when 0 then b.课时 else 0 end), 累计选择课时 = sum(b.课时) from #a a join #b b on a.课程号 = b.课程号 join #c c on a.用户号 = c.用户号 join #d d on c.班级号 = d.班级号 group by a.用户号, c.用户名称, d.班级名称/* 用户号 用户名称 班级名称 未审核课时 累计选择课时 -------- -------- -------- ----------- ----------- U01 张三 班级1 30 60 U02 李四 班级2 20 30 */
select A.用户号 ,C.用户名 ,D.班级名称, 未审核课时 = sum(case when a.选择状态=0 then b.课时 else 0 end), 累计选择课时 = sum (b.课时 ) from A , B , C , D where a.用户号=c.用户号 and c.班级号=d.班级号 and a.课程号=b.课程号 group by A.用户号 ,C.用户名 ,D.班级名称 having min(a.选择状态)=0
if object_id('tempdb.dbo.#a') is not null drop table #a
create table #a(用户号 varchar(8), 课程号 varchar(8), 选择状态 int)
insert into #a
select 'U01', 'L01', 1 union all
select 'U01', 'L02', 1 union all
select 'U01', 'L03', 0 union all
select 'U02', 'L01', 1 union all
select 'U02', 'L02', 0
--> 测试数据:#b
if object_id('tempdb.dbo.#b') is not null drop table #b
create table #b(课程号 varchar(8), 课程名称 varchar(8), 课时 int)
insert into #b
select 'L01', '课程A', 10 union all
select 'L02', '课程B', 20 union all
select 'L03', '课程C', 30
--> 测试数据:#c
if object_id('tempdb.dbo.#c') is not null drop table #c
create table #c(用户号 varchar(8), 用户名称 varchar(8), 班级号 varchar(8))
insert into #c
select 'U01', '张三', 'C01' union all
select 'U02', '李四', 'C02'
--> 测试数据:#d
if object_id('tempdb.dbo.#d') is not null drop table #d
create table #d(班级号 varchar(8), 班级名称 varchar(8))
insert into #d
select 'C01', '班级1' union all
select 'C02', '班级2'select
a.用户号,
c.用户名称,
d.班级名称,
未审核课时 = sum(case a.选择状态 when 0 then b.课时 else 0 end),
累计选择课时 = sum(b.课时)
from #a a
join #b b on a.课程号 = b.课程号
join #c c on a.用户号 = c.用户号
join #d d on c.班级号 = d.班级号
group by
a.用户号,
c.用户名称,
d.班级名称/*
用户号 用户名称 班级名称 未审核课时 累计选择课时
-------- -------- -------- ----------- -----------
U01 张三 班级1 30 60
U02 李四 班级2 20 30
*/
未审核课时 = sum(case when a.选择状态=0 then b.课时 else 0 end),
累计选择课时 = sum (b.课时 )
from A , B , C , D
where a.用户号=c.用户号
and c.班级号=d.班级号
and a.课程号=b.课程号
group by A.用户号 ,C.用户名 ,D.班级名称
having min(a.选择状态)=0
对,最后应该加上 having min(a.选择状态)=0