简体   繁体   English

动态查询双向频率表或交叉表/数据透视表问题

[英]Dynamic query for two way frequency table or crosstab/pivot issue

I have a database model with table name work having two columns Category and Agegroup. 我有一个具有表名称的数据库模型,该模型具有两列Category和Agegroup。 My table(just an example) is: 我的表(只是一个例子)是:

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

I want the output like this: 我想要这样的输出:

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

I have a dynamic query like this but I'm getting in a different way. 我有一个像这样的动态查询,但是我得到了不同的方式。

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)

Kindly provide your inputs to help. 请提供您的意见以提供帮助。 Category 1 is apple, 2 is orange and so on.. 类别1是苹果,类别2是橙色,依此类推。

My output: 我的输出:

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

and so on.. 等等..

I didn't use SQL Server for a decade, but that's how the resulting query would look in in MySQL: 我已经十年没有使用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;

Try the following resulting SQL in SQL server, and if it gives you the correct data, you "just" will have to do it dynamic... 在SQL Server中尝试以下生成的SQL,如果它为您提供了正确的数据,则您“必须”就必须动态地进行处理...

But maybe there is better fix using the 'pivot' function form SQL Server? 但是,也许使用SQL Server的“数据透视”功能可以更好地解决此问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM