I have a database model with table name work having two columns Category and 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..

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:

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...

But maybe there is better fix using the 'pivot' function form SQL Server?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top