-8

我想连续返回一名学生,这是我的选择:

select Name from student

结果:

 Name
 Emre 

我的第二个选择是我的老师,但我仍然想带一排:

select Name from teacher

结果:

Name
 John 
 Adam

我想要这个输出

 Name   1.Teacher   2.Teacher
 Emre   John        Adam

是否有可能在一行中做到这一点?

4

1 回答 1

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;

请参阅带有演示的 SQL Fiddle

于 2013-09-17T14:55:11.360 回答