您将需要执行PIVOT
. 使用 PIVOT 有两种方法可以做到这一点,一种是您对要转换的列进行编码的静态 Pivot,另一种是在执行时确定列的动态 Pivot。
静态枢轴,您将需要对值进行硬编码:
select name,
IsNull([701-730], '') [701-730],
IsNull([731-800], '') [731-800],
IsNull([801-830], '') [801-830],
IsNull([831-900], '') [831-900]
from
(
select e.name,
cast(e.starttime as varchar(10))+'-'
+cast(e.endtime as varchar(10)) Session,
m.FirstName
from
(
select *
from tblEmployees e
cross apply RefSessions
) e
left join tblBookSession b
on e.EmployeeID = b.EmployeeID
and e.sessionid = b.sessionid
left join tblMembers m
on b.MemberNo = m.MemberNo
) x
pivot
(
max(FirstName)
for session in ([701-730], [731-800], [801-830], [831-900]) -- additional sessions here
)p
请参阅带有演示的 SQL Fiddle
如果您有许多值要转换为列或未知数量的值,那么您将需要使用动态 sql 版本PIVOT
:
DECLARE @cols AS NVARCHAR(MAX),
@colsPivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ','
+ QUOTENAME(cast(starttime as varchar(10))
+'-'+cast(endtime as varchar(10)))
from RefSessions
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsPivot = STUFF((SELECT ', IsNull('
+ QUOTENAME(cast(starttime as varchar(10))
+'-'+cast(endtime as varchar(10))) +', '''') as [' +
cast(starttime as varchar(10))
+'-'+cast(endtime as varchar(10)) + ']'
from RefSessions
group by SessionID, starttime, endtime
order by SessionID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT name, ' + @colsPivot + ' from
(
select e.name,
cast(starttime as varchar(10))+''-''
+cast(endtime as varchar(10)) Session,
m.FirstName
from
(
select *
from tblEmployees e
cross apply RefSessions
) e
left join tblBookSession b
on e.EmployeeID = b.EmployeeID
and e.sessionid = b.sessionid
left join tblMembers m
on b.MemberNo = m.MemberNo
) x
pivot
(
max(FirstName)
for Session in (' + @cols + ')
) p '
execute(@query)
请参阅带有演示的 SQL Fiddle