给出以下SQL表:
GroupAvailable, GroupAssigned, Title
----------------------------------------
GroupA,GroupA,Widget1
GroupA,GroupB,Widget1
GroupB,GroupA,Widget1
需要一份报告:
Widget1
GroupA GroupB
GroupA X X
GroupB X
Widget2
etc.
这可以在查询中执行吗?还是非常接近的东西?或者代码和SQL的组合会更好吗?
答案 0 :(得分:4)
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获取结果:
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);
两个版本都会给出结果:
| NAME | GROUPA | GROUPB |
------------------------------------
| Widget1 GroupA | X | X |
| Widget1 GroupB | X | |
| Widget2 GroupB | X | |