日期:2014-05-19  浏览次数:20435 次

求:对一个范围内的数据进行分组汇总的实现
我想对一个范围内的数据进行分组汇总,比如用户年龄在21-30、31-40、41-50的做一个分组汇总,该怎么实现?

------解决方案--------------------
表:
ID ,年龄
1,20
2,40

select ID,sum(case when 年龄> 21 and年龄 <30 then num ),sum(case when 年龄> 31 and年龄 <40 then num ),......
from 表
group by ID
------解决方案--------------------
create table #a (a int, b int)

insert into #a
select 1,20 union all
select 2,22 union all
select 3,28 union all
select 4,22 union all
select 5,30 union all
select 6,37 union all
select 7,34


select max(a),count(a) from #a group by (b-1)/10

这个意思嘛?
------解决方案--------------------
select 年龄段, ...
from
(
select 年龄,case when 年龄 between 21 and 30 then [21-30],
when 年龄 between 31 and 40 then [31-40],
when 年龄 between 41 and 50 then [41-50] end as 年龄段,
...
from tablename
)tab
group by 年龄段

当然也可以只写一层查询,不过看起来没有这么清晰