有一个机器表
cityid machineID,statusID。现在要出来一个按照城市名排列的各地有效机器数量,总数量 和比例的表。第一部分算总的可以select count(machineID),cityID from machineTable groupBy cityid orderby cityid算有效的(statusid=1 代表有效)可以select count(machineID),cityID from machineTable where statudid =1 groupBy cityid orderby cityid如何在一个sql中得出
 cityid,总机器数,有效机器数,有效机器/总机器数

解决方案 »

  1.   

    我也不知道可以不,思路貌似是对的。select cityid, count(machineid) c1,
    sum(decode(statusid,1,1,0)) s1, 
    c1/s1 from machineTable 
    groupBy cityid orderby cityid
      

  2.   


    with machineTable
    as
    (
    select '北京' cityid, 1 as statusid,'AAA' as machineID from dual
    union
    select '北京' , 0 ,'BBB'  from dual
    union
    select '北京' , 0 ,'CCC'  from dual
    union
    select '广州' , 1 ,'DDD'  from dual
    union
    select '上海' , 0 ,'EEE'  from dual
    )
    select mar.*
     ,decode(a,'0','0',decode(b,'0','0',100*ROUND(b/a,4)||'%'))as c 
    from
    (
    select distinct cityid
    ,sum(case when 1=1 then 1 else 0 end) over(partition by cityid) a
    ,sum(case when 1=1 and statusid=1 then 1 else 0 end) over(partition by cityid) b
     from machineTable 
    ) mar 
    --执行结果
    1 广州 1 1 100%
    2 上海 1 0 0
    3 北京 3 1 33.33%