SQL Server-创建数据透视的简单方法
是否有人知道一种简单的方法来创建此结果的轴心:SQL Server-创建数据透视的简单方法,sql,sql-server-2008-r2,Sql,Sql Server 2008 R2,是否有人知道一种简单的方法来创建此结果的轴心: [0-1] [1-2] [2-3] [3-4] 12 45 29 5 此结果是通过以下查询创建的: SELECT [0-1] = SUM(CASE WHEN AGE >= 0 AND AGE <= 1 THEN 1 ELSE 0 END), [1-2] = SUM(CASE WHEN AGE > 1 AND AGE <= 2 THEN 1 ELSE 0 END),
[0-1] [1-2] [2-3] [3-4]
12 45 29 5
此结果是通过以下查询创建的:
SELECT [0-1] = SUM(CASE WHEN AGE >= 0 AND AGE <= 1 THEN 1 ELSE 0 END),
[1-2] = SUM(CASE WHEN AGE > 1 AND AGE <= 2 THEN 1 ELSE 0 END),
[2-3] = SUM(CASE WHEN AGE > 2 AND AGE <= 3 THEN 1 ELSE 0 END)
FROM dbo.Persons
也欢迎链接到文章/博客。请推荐一种简单易用的解决方案。这里有一种使用
交叉连接和聚合的方法:
select ages.minage, ages.maxage,
sum(case when age > ages.minage and age <= ages.maxage then 1 else 0 end) as cnt
from dbo.Persons cross join
(select -1 as minage, 1 as maxage union all
select 1, 2 union all
select 2, 3
) as ages
group by ages.minage, ages.maxage
选择ages.minage、ages.maxage、,
sum(age>ages.minage和age get错误时的情况):“列'ages.minage'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”
select ages.minage, ages.maxage,
sum(case when age > ages.minage and age <= ages.maxage then 1 else 0 end) as cnt
from dbo.Persons cross join
(select -1 as minage, 1 as maxage union all
select 1, 2 union all
select 2, 3
) as ages
group by ages.minage, ages.maxage