我想在一行中返回一名学生,这是我的选择:
select Name from student
结果:
Name
Emre
我的第二个选择是我的老师,但我仍然希望带一行:
select Name from teacher
结果:
Name
John
Adam
我想要这个输出
Name 1.Teacher 2.Teacher
Emre John Adam
有可能在一行中完成吗?
答案 0 :(得分:2)
很遗憾,您没有提供有关student
如何与每个teacher
相关联的任何详细信息,所以我假设您有一个表连接两个类似于以下内容的表:
CREATE TABLE student_teacher
([student_id] int, [teacher_id] int)
;
如果您有这种类型的连接表,那么您可以使用PIVOT函数来获得结果。如果每个学生的教师数量有限,那么您可以使用row_number()
对查询进行硬编码,为每位学生的每个教学分配一个排序值:
select student_name, teacher1, teacher2
from
(
select s.name student_name,
t.name teacher_name,
'teacher'
+ cast(row_number() over(partition by s.id
order by t.id) as varchar(10)) seq
from student s
inner join student_teacher st
on s.id = st.student_id
inner join teacher t
on st.teacher_id = t.id
) d
pivot
(
max(teacher_name)
for seq in (teacher1, teacher2)
) piv;
见SQL Fiddle with Demo。但是,如果你有一定数量的教师,那么你将看到使用动态SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ', ' + QUOTENAME('teacher'
+cast(row_number() over(partition by student_id
order by teacher_id) as varchar(10)))
from student_teacher
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT student_name,' + @cols + '
from
(
select s.name student_name,
t.name teacher_name,
''teacher''
+ cast(row_number() over(partition by s.id
order by t.id) as varchar(10)) seq
from student s
inner join student_teacher st
on s.id = st.student_id
inner join teacher t
on st.teacher_id = t.id
) x
pivot
(
max(teacher_name)
for seq in (' + @cols + ')
) p '
execute sp_executesql @query;