34,593
社区成员
发帖
与我相关
我的任务
分享
select 课程代码 = CourseCode
, 状态0 = (select count(Type) from ExemptStudent where CourseCode = e.CourseCode and Type = 0)
, 状态1 = (select count(Type) from ExemptStudent where CourseCode = e.CourseCode and Type = 1)
, 状态为0的学生ID = stuff((select ',' + StudentID from ExemptStudent where CourseCode = e.CourseCode and Type = 0 for xml path('')),1,1,'')
, 状态为1的学生ID = stuff((select ',' + StudentID from ExemptStudent where CourseCode = e.CourseCode and Type = 1 for xml path('')),1,1,'')
from ExemptStudent e
group by CourseCode
--> 测试数据: [ExemptStudent]
if object_id('[ExemptStudent]') is not null drop table [ExemptStudent]
create table [ExemptStudent] (ID varchar(36),Semester varchar(36),CourseCode datetime,Type int,ClassID varchar(36),StudentID varchar(36))
insert into [ExemptStudent]
select '9a78c2b7-bef2-44b8-a560-8169efbbe0eb','a6731776-0663-4155-9246-12906134b509','30031003',0,'d9bd5111-d444-47e6-82f5-01c449618a4a','ea182e26-0af7-4326-b1e5-2a341a93e1d2' union all
select '5c07ebb7-b6ee-4cea-8206-a6724186614e','a6731776-0663-4155-9246-12906134b509','30031001',0,'d9bd5111-d444-47e6-82f5-01c449618a4a','2310e6b3-605d-4cd7-8ca0-e4b50d430977' union all
select 'e5696bcb-a9c0-4b57-b807-aaf25c4a3c53','a6731776-0663-4155-9246-12906134b509','30031001',0,'d9bd5111-d444-47e6-82f5-01c449618a4a','eb05be12-56a5-4dba-883d-3c636b9f3e22' union all
select 'feebcef7-d19e-4b27-954c-ac91ad72ecc4','a6731776-0663-4155-9246-12906134b509','30031003',1,'d9bd5111-d444-47e6-82f5-01c449618a4a','2310e6b3-605d-4cd7-8ca0-e4b50d430977' union all
select '29574120-aed8-4852-9e3c-e3e577c8dbe3','a6731776-0663-4155-9246-12906134b509','30031003',0,'d9bd5111-d444-47e6-82f5-01c449618a4a','eb05be12-56a5-4dba-883d-3c636b9f3e22' union all
select '4b80ebdc-fa52-46ca-8445-fc3c3945faa7','a6731776-0663-4155-9246-12906134b509','30031001',1,'d9bd5111-d444-47e6-82f5-01c449618a4a','ea182e26-0af7-4326-b1e5-2a341a93e1d2'
go
create function get_studentid(@CourseCode varchar(40),@type int)
returns varchar(500)
as
begin
declare @sql varchar(500)
select @sql=isnull(@sql+',','')+ltrim(studentid) from ExemptStudent where CourseCode=@CourseCode and type=@type
return @sql
end
go
select coursecode,[状态为0]=sum(case type when 0 then 1 else 0 end),
[状态为1]=sum(case type when 1 then 1 else 0 end),
[状态为0的学生ID]=dbo.get_studentid(coursecode,0),[状态为1的学生ID]=dbo.get_studentid(coursecode,1)
from [ExemptStudent]
group by coursecode
--结果:
coursecode 状态为0 状态为1 状态为0的学生ID 状态为1的学生ID
----------------------- ----------- ----------- --------------------------------------------------------------------------
3003-10-01 00:00:00.000 2 1 2310e6b3-605d-4cd7-8ca0-e4b50d430977,eb05be12-56a5-4dba-883d-3c636b9f3e22 ea182e26-0af7-4326-b1e5-2a341a93e1d2
3003-10-03 00:00:00.000 2 1 ea182e26-0af7-4326-b1e5-2a341a93e1d2,eb05be12-56a5-4dba-883d-3c636b9f3e22 2310e6b3-605d-4cd7-8ca0-e4b50d430977