日期:2014-05-17  浏览次数:20480 次

求一条SQL优化,不用嵌套
;with #t as (
select 'gao_ps' ss,'192.168.0.1' ip,1 is_reg,1 has_code
union all select 'gao_ps','192.168.0.1',1,1
union all select 'gao_ps','192.168.1.1',1,1
union all select 'gao_ps','192.168.1.1',0,1
)
/* 从这里开始有没有办法不用嵌套 */
select ss,SUM(注册个数) 注册个数,
SUM(弹代码数) 弹代码数,
SUM(case when 注册个数>=2 then 注册个数 else 0 end) 重复IP注册数
from (
select ss,ip,COUNT(1) 注册个数,
SUM(case when has_code=1 then 1 else 0 end) 弹代码数
from #t 
where is_reg=1
group by ss,ip) a 
group by ss


有没有办法一条SQL搞定不用嵌套或者零时表,求高手解答!

------解决方案--------------------
貌似没办法不嵌套
------解决方案--------------------
聚合函数不能嵌套,所以你这个不能一句话搞定
------解决方案--------------------
这个不能不嵌套,只能这么做,你写的已经不错了。
------解决方案--------------------
try this,

with #t as 
(select 'gao_ps' ss,'192.168.0.1' ip,1 is_reg,1 has_code union all 
 select 'gao_ps','192.168.0.1',1,1 union all 
 select 'gao_ps','192.168.1.1',1,1 union all 
 select 'gao_ps','192.168.1.1',0,1
)
select ss,
       count(1) '注册个数',
       sum(case when has_code=1 then 1 else 0 end) '弹代码数',
       count(distinct ip) '重复IP注册数'
 from #t
 where is_reg=1
 group by ss
 
/*
ss     注册个数       弹代码数     重复IP注册数
------ ----------- ----------- -----------
gao_ps  3           3            2

(1 row(s) affected)
*/

------解决方案--------------------
引用:
try this,

with #t as 
(select 'gao_ps' ss,'192.168.0.1' ip,1 is_reg,1 has_code union all 
 select 'gao_ps','192.168.0.1',1,1 union all 
 select 'gao_ps','192.168.1.1',1,1 union all 
 select 'gao_ps','192.168.1.1',0,1
)
select ss,
       count(1) '注册个数',