动态查询双向频率表或交叉表/枢轴问题

时间:2014-03-02 20:39:04

标签: sql sql-server tsql dynamic-sql sqlxml

我有一个数据库模型,表名工作有两列Category和Agegroup。我的表(只是一个例子)是:

Category     Agegroup
    1       2-4
    2       7-9
    1       9-11
    3       7-9
    2       7-9
    1       2-4
    3       2-4 
    1       9-11

我希望输出如下:

Category   2-4   7-9   9-11
   1        2     0     2
   2        0     2     0
   3        1     1     0

我有这样的动态查询,但我的方式不同。

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Agegroup) 
                    from dbo.model
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Category,' + @cols + ' 
            from dbo.model
            pivot 
            (
                count(Agegroup)
                for Agegroup in (' + @cols + ')
            ) p '

execute(@query)

请提供帮助。第1类是苹果,2是橙色等等。

我的输出:

Category 2-4 7-9 9-11
  1       1   0   0
  1       1   0   0
  2       0   1   0
  1       0   0   1 

依旧......

1 个答案:

答案 0 :(得分:0)

我没有使用SQL Server十年,但这就是结果查询在MySQL中的样子:

select Category, sum(if(Agegroup='2-4',1,0)), sum(if(Agegroup='7-9',1,0)), sum(if(Agegroup='9-11',1,0))
from dbo.model
group by Category;

在SQL Server中尝试以下生成的SQL,如果它为您提供了正确的数据,那么您“只需”动态地执行它...

但也许有更好的修复使用SQL Server的'pivot'功能?

相关问题