今天在幫客戶(hù)做一些統(tǒng)計(jì),需要按照某個(gè)區(qū)段對(duì)數(shù)據(jù)進(jìn)行統(tǒng)計(jì),于是上網(wǎng)搜索了一下,結(jié)果沒(méi)有發(fā)現(xiàn)比較滿(mǎn)意的,最接近的是 中7樓的答案,但這個(gè)統(tǒng)計(jì)不能指定區(qū)段,于是自己琢磨了一下,寫(xiě)了這么個(gè)語(yǔ)句:
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
我是根據(jù)每一個(gè)指定的區(qū)段進(jìn)行一次比值,并將起轉(zhuǎn)換成bit類(lèi)型,這樣得到的結(jié)果要么是符合條件1,要么是不符合區(qū)段0,然后在整個(gè)group就可以得到結(jié)果了
當(dāng)然,我沒(méi)有把統(tǒng)計(jì)得到的區(qū)段也方到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)
這樣,就得到了我們所需要的區(qū)段統(tǒng)計(jì)了
更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄