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 甲类固话 415352
1003 后付费小灵通 90304
1006 无线农话5760
1010 乙类固话 448
1022 公话 2720
1027 公话 40
1028 公话 30
1813 预付费小灵通 327
其中 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 when serv_type_ in(1022,1027,1028) then 1022 else serv_type_ end),s_name