是否可以在给定单个数据库表的sql查询中生成报告矩阵作为结果集

时间:2013-07-09 23:01:17

标签: c# sql sql-server

给出以下SQL表:

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

需要一份报告:

Widget1
               GroupA     GroupB

GroupA           X          X
GroupB           X


Widget2
etc.

这可以在查询中执行吗?还是非常接近的东西?或者代码和SQL的组合会更好吗?

1 个答案:

答案 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 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 with Demo

两个版本都会给出结果:

|           NAME | GROUPA | GROUPB |
------------------------------------
| Widget1 GroupA |      X |      X |
| Widget1 GroupB |      X |        |
| Widget2 GroupB |      X |        |