今天在幫客戶做一些統計,需要按照某個區段對數據進行統計,於是上網搜索了一下,結果沒有發現比較滿意的,最接近的是 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)
這樣,就得到了我們所需要的區段統計了