今天在帮客户做一些统计,需要按照某个区段对数据进行统计,于是上网搜索了一下,结果没有发现比较满意的,最接近的是 http://bbs.csdn.net/topics/70184424 中7楼的答案,但这个统计不能指定区段,于是自己琢磨了一下,写了这么个语句:
declare @tb table(id int identity(1,1),num int)
insert into @tb(num) values(1),(10),(20),(25),(12),(15),(13),(22),(5),(50),(80),(110)
select count(*),overall,over10,over20,over50,over100 from (select 1 as overall,convert(bit,num/10) as over10,convert(bit,num/20) as over20,convert(bit,num/50) as over50,convert(bit,num/100) as over100 from @tb) as a group by overall,over10,over20,over50,over100
我是根据每一个指定的区段进行一次比值,并将起转换成bit类型,这样得到的结果要么是符合条件1,要么是不符合区段0,然后在整个group就可以得到结果了
当然,我没有把统计得到的区段也方到sql里,于是修改一下Sql指令
declare @tb table(id int identity(1,1),num int)
insert into @tb(num) values(1),(10),(20),(25),(12),(15),(13),(22),(5),(50),(80),(110)
select N'scope'=(case(overall+over10+over20+over50+over100) when 1 then '0-9' when 2 then '10-19' when 3 then '20-49' when 4 then '50-99' else '100+' end),count(*) from (select 1 as overall,convert(bit,num/10) as over10,convert(bit,num/20) as over20,convert(bit,num/50) as over50,convert(bit,num/100) as over100 from @tb) as a group by (overall+over10+over20+over50+over100)
这样,就得到了我们所需要的区段统计了