客户表:ct(cid,cnum,cname)
订单表:dt(did,cid)
结算表:jt(jid,did,jfs)
统计目标:
统计每次结算都是使用现金的客户数据,得到下面这样的结果:
----------------------------------------------
客户ID  客户编号  客户名称  全部结算次数  现金次数
1       001      张三      5            5
2       010      李四      9            9
3       100      王五      6            6
----------------------------------------------select ct.cid 客户ID,ct.cnum 客户编号,ct.cname 客户名称,count(jt.did) 全部结算次数,count(jt.jfs) 现金次数
from  ct,dt,jt
where ct.cid = dt.cid
and   dt.did = jt.did
and   jt.jsf = '现金'
group by ct.cid,ct.cnum,ct.mingcheng
having count(jt.did) = count(jt.jfs)
order by ct.cid asc上面这段代码只能查询到客户使用现金次数的数据,与统计目标完全不同,请教该如何修改语句才能达到目的?

解决方案 »

  1.   

    select ct.cid 客户ID,ct.cnum 客户编号,ct.cname 客户名称,count(jt.did) 全部结算次数,sum(case when jt.jfs='现金' then 1 else 0 end) 现金次数
    from  ct,dt,jt
    where ct.cid = dt.cid
    and   dt.did = jt.did
    group by ct.cid,ct.cnum,ct.mingcheng
    order by ct.cid asc
      

  2.   

    having count(jt.did)=sum(case when jt.jfs='现金' then 1 else 0 end) 
    加上不就行了
      

  3.   

    select kehu.kh_id 客户ID,kehu.jianma 客户编号,kehu.mingcheng 客户名称,count(huidan_mingxi.huidan_id) 全部结算次数,sum(case when huidan_mingxi.huifufangshi = '现金'
                                                                                                                                   then 1
                                                                                                                                   else 0
                                                                                                                                   end) 现金次数
    from  kehu,huidan,huidan_mingxi
    where kehu.kh_id = huidan.kh_id
    and   huidan.huidan_id = huidan_mingxi.huidan_id
    group by kehu.kh_id,kehu.jianma,kehu.mingcheng
    having count(huidan_mingxi.huidan_id) = sum(case when huidan_mingxi.huifufangshi = '现金' then 1 else 0 end)
    order by kehu.kh_id asc
    刚刚搞定,就漏了个having