0

有谁知道创建此结果的轴的简单方法:

[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

我想将列值显示为行,即输出应如下所示:

[0-1]      12
[1-2]      45
[2-3]      29
[3-4]       5

也欢迎链接到文章/博客。请提出一个简单易懂的解决方案。

4

1 回答 1

1

这是一种使用cross join和聚合的方式:

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

我喜欢这种方法,因为它很容易添加新的年龄范围。请注意,这也包括范围。

于 2013-08-21T10:49:30.830 回答