PIVOT函数将使您接近结果:
select name,
coalesce(GroupA, '') GroupA,
coalesce(GroupB, '') GroupB
from
(
select title +' '+ groupavailable name,
groupassigned,
'X' as flag
from yourtable
) d
pivot
(
max(flag)
for groupassigned in (GroupA, GroupB)
) piv;
请参阅SQL Fiddle with Demo。
如果您有未知数量的组,那么您可以使用动态 SQL 来获取结果:
DECLARE @cols AS NVARCHAR(MAX),
@colsNull AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(GroupAvailable)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsNull = STUFF((SELECT distinct ', coalesce(' + QUOTENAME(GroupAvailable)+', '''') as '+QUOTENAME(GroupAvailable)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT name,' + @colsNull + '
from
(
select title +'' ''+ groupavailable name,
groupassigned,
''X'' as flag
from yourtable
) x
pivot
(
max(flag)
for groupassigned in (' + @cols + ')
) p '
execute(@query);
请参阅带有演示的 SQL Fiddle
两个版本都会给出结果:
| NAME | GROUPA | GROUPB |
------------------------------------
| Widget1 GroupA | X | X |
| Widget1 GroupB | X | |
| Widget2 GroupB | X | |