create table [流水表]
([姓名] nvarchar(30),
[班级] nvarchar(30),
[备注] nvarchar(30))
create table [课程代码表]
([姓名] nvarchar(30),
[一班] int, [二班] int , [三班] int)
insert into [流水表] values('张三', '二班', '备注1'),
('李四', '三班', '备注2'),
('王五', '二班', '备注3'),
('赵六', '一班', '备注4'),
('张三', '一班', '备注5')
insert into [课程代码表] values('张三', 1, 2 ,3 ),
('李四', 4, 5 ,6 ),
('王五', 7, 8 ,9 ),
('赵六', 1 ,2, 3 )
go
---1 行列转换
/*
SELECT [姓名],[班级],[课程代码]
from [课程代码表]
unpivot([课程代码] for [班级] in([一班] , [二班] , [三班]))as test
go
*/
---2 左连接
select a.[姓名],b.[课程代码],a.[班级],a.[备注] from [流水表] as a
left join (
SELECT [姓名],[课程代码],[班级]
from [课程代码表]
unpivot([课程代码] for [班级] in([一班] , [二班] , [三班]))as test
) as b on a.[姓名] = b.[姓名]
and a.[班级] = b.[班级]
go
drop table [流水表]
drop table [课程代码表]
这个问题 有什么问题吗???想查几列就查几列啊??不是很明白你的问题。