create table 班干部表
(职务 varchar(10),学生ID int)insert into 班干部表
select '班长',4 union all
select '学习委员',2 union all
select '文娱委员',3 union all
select '体育委员',5create table 学生信息表
(学生ID int,姓名 varchar(10),年龄 int,性别 varchar(2),爱好 varchar(10))
insert into 学生信息表
select 1,'关羽',10,'男',null union all
select 2,'诸葛亮',9,'男',null union all
select 3,'貂蝉',11,'女',null union all
select 4,'刘备',10,'男',null union all
select 5,'张飞',9,'男',null
select *,identity(int,1,1) 'rn'
into #t
from 班干部表select a.职务,b.姓名,a.rn
into #u
from #t a
inner join 学生信息表 b on a.学生ID=b.学生ID
order by a.rn
declare @tsql varchar(6000)select @tsql=isnull(@tsql+',','')
+'max(case when rn='+rtrim(number)+' then 姓名 else '''' end) '''
+(select 职务 from #u where rn=number)+''' '
from master.dbo.spt_values
where type='P' and number between 1 and (select max(rn) from #u)select @tsql='select '+@tsql+' from #u'exec(@tsql)/*
班长 学习委员 文娱委员 体育委员
---------- ---------- ---------- ----------
刘备 诸葛亮 貂蝉 张飞(1 row(s) affected)
*/
现在要得到 表3 的结果,这个查询语句该怎样写?请大侠指教。
(班级ID int,
班长 int,
学习委员 int,
文娱委员 int,
体育委员 int)insert into 班干部表
values(1,4,2,3,5),
(2,6,7,9,1),
(3,12,13,14,15),
(4,16,17,18,19)select * from 班干部表create table 学生信息表
(学生ID int,
姓名 char(10),
年龄 int check (年龄>6 and 年龄<60),
性别 char(2),
爱好 char(20))insert into 学生信息表
values(1,'关羽',10,'男',null),
(2,'诸葛亮',9,'男',null),
(3,'貂蝉',11,'女',null),
(4,'刘备',10,'男',null),
(5,'张飞',9,'男',null),
(6,'曹操',12,'男',null),
(7,'夏侯淳',13,'男',null),
(8,'小乔',10,'女',null),
(9,'大乔',10,'女',null)select * from 学生信息表select * from 班干部表select 班级ID,(select 姓名 from 学生信息表 where 学生ID=班长) as 班长,
(select 姓名 from 学生信息表 where 学生ID=学习委员) as 学习委员,
(select 姓名 from 学生信息表 where 学生ID=文娱委员) as 文娱委员,
(select 姓名 from 学生信息表 where 学生ID=体育委员) as 体育委员 from 班干部表
where (select 姓名 from 学生信息表 where 学生ID=班长) is not null结果图如下: