group by 的分类问题
先说说表结构:
表 dhzl3 中有字段serv_state表示 状态,serv_type_ 为设备类别
表 serv_ty_name 中有字段 id ,s_name为设备名称,这个表我主要是用来根据serv_type_ 的值来重命名的
我的分类查询语句如下:
select
serv_type_, s_name=(SELECT s_name FROM serv_ty_name WHERE id=serv_type_),
sum(case when serv_state= 'F1N ' then 1 else 0 end) as 新装,
sum(case when serv_state= 'F1R ' then 1 else 0 end) as 拆机,
sum(case when serv_state= 'F1S ' then 1 else 0 end) as 停机,
sum(case when serv_state!= 'F1R ' then 1 else 0 end) as 到达数
from dhzl3
where serv_type_ in (1000,1010,1003,1813,1006,1022,1027,1028)
group by serv_type_
order by serv_type_
查询结果如下:
serv_type_ s_name 新装 拆机
1000 甲类固话 415 352
1003 后付费小灵通 90 304
1006 无线农话 576 0
1010 乙类固话 44 8
1022 公话 27 20
1027 公话 4 0
1028 公话 3 0
1813 预付费小灵通 32 7
其中 1022,1027,1028 都是公话,但是是不同类型的公话,实际的情况是,我不需要分不同类型的公话,我要把1022,1027,1028 都只当作公话来看待,于是我要把这三种类型的公话的新装和拆机数给合计起来,我该怎么办?
----------------------
问题长,看起来麻烦,所以,50分献给各位大大!
------解决方案--------------------如上语句建立视图
然后select 视图 group by s_name
------解决方案--------------------改三处可以不用建视图
select (case when serv_type_ in(1022,1027,1028) then 1022 else serv_type_ end)-------------1
serv_type_, s_name=(SELECT s_name FROM serv_ty_name WHERE id=serv_type_),
sum(case when serv_state= 'F1N ' then 1 else 0 end) as 新装,
sum(case when serv_state= 'F1R ' then 1 else 0 end) as 拆机,
sum(case when serv_state= 'F1S ' then 1 else 0 end) as 停机,
sum(case when serv_state!= 'F1R ' then 1 else 0 end) as 到达数
from dhzl3
where serv_type_ in (1000,1010,1003,1813,1006,1022,1027,1028)
group by (case when serv_type_ in(1022,1027,1028) then 1022 else serv_type_ end)-----------2
order by (case when serv_type_ in(1022,1027,1028) then 1022 else serv_type_ end)-----------3
------解决方案--------------------这样改试试
select (case when serv_type_ in(1022,1027,1028) then 1022 else serv_type_ end),
s_name,
sum(case when serv_state= 'F1N ' then 1 else 0 end) as 新装,
sum(case when serv_state= 'F1R ' then 1 else 0 end) as 拆机,
sum(case when serv_state= 'F1S ' then 1 else 0 end) as 停机,
sum(case when serv_state!= 'F1R ' then 1 else 0 end) as 到达数
from dhzl3
inner join serv_ty_name on serv_ty_name.id=case when serv_type_ in(1022,1027,1028) then 1022 else serv_type_ end
where serv_type_ in (1000,1010,1003,1813,1006,1022,1027,1028)
group by (case wh