原始数据是这样的 ,先要统计出来每个地区出现的次数 然后在 调出前4名 剩下的显示成其他
id address_sheng
1 黑龙
2 黑龙
3 山东
4 河北
5 河北
6 吉林
7 山东
8 河北
9 河北
10 吉林
11 山东
想要的效果
ddress_sheng Shengsum
河北 4
山东 3
吉林 2
其他 51
现在我用的一条SQL 语句,只能实现 所有的统计出来,不能实现取前几名和其他
select SUBSTRING(address_sheng,1,2) address_sheng ,count(address_sheng) Shengsum
from Kehu_Info
WHERE hezuoZt='1' group by address_sheng ORDER BY Shengsum DESC
结果
address_sheng Shengsum
黑龙 1042
辽宁 816
山东 718
河北 463
内蒙 427
吉林 356
山西 126
北京 119
河南 108
湖南 105
陕西 93
江苏 90
湖北 50
云南 47
四川 42
重庆 40
甘肃 37
安徽 33
江西 2
------解决思路----------------------
手誤,不好意思。再測試一下。
select *,identity(int,1,1) as rn into #temp from (
select SUBSTRING(address_sheng,1,2) address_sheng ,count(address_sheng) Shengsum
from Kehu_Info
WHERE hezuoZt='1' group by address_sheng) as a order by Shengsum desc
select address_sheng,sum(Shengsum) from (
select case when rn<5 then address_sheng else '其他' end as address_sheng,
Shengsum from #temp as b) as c
group by address_sheng
drop table #temp