1

给定以下 SQL 表:

GroupAvailable, GroupAssigned, Title
----------------------------------------
GroupA,GroupA,Widget1
GroupA,GroupB,Widget1
GroupB,GroupA,Widget1

需要一个看起来像这样的报告:

Widget1
               GroupA     GroupB

GroupA           X          X
GroupB           X


Widget2
etc.

这可以在查询中做到吗?或者非常接近的东西?或者代码和sql的组合会更好吗?

4

1 回答 1

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 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 |        |
于 2013-07-09T23:13:58.370 回答