我有一个数据库模型,表名为work,有两个列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)
请提供您的输入以提供帮助。第一类是苹果,第二类是橙色等等。
我的输出:
Category 2-4 7-9 9-11
1 1 0 0
1 1 0 0
2 0 1 0
1 0 0 1
以此类推..
发布于 2014-03-03 06:05:14
我有十年没有使用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”函数?
https://stackoverflow.com/questions/22133145
复制相似问题