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