首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

字段值出现次数与记要总数相等的查询统计

2012-12-24 
字段值出现次数与记录总数相等的查询统计客户表:ct(cid,cnum,cname)订单表:dt(did,cid)结算表:jt(jid,did,

字段值出现次数与记录总数相等的查询统计
客户表: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

上面这段代码只能查询到客户使用现金次数的数据,与统计目标完全不同,请教该如何修改语句才能达到目的?
[最优解释]
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
[其他解释]
引用:
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.c……

------------------------------------------
这样确实查出了客户的总结算次数和使用现金的次数,统计目标比这个更细一点,要的是其中总结算次数与使用现金次数相等的数据——即查询每次结算都是使用现金的。
[其他解释]
having count(jt.did)=sum(case when jt.jfs='现金' then 1 else 0 end) 
加上不就行了
[其他解释]
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

热点排行
Bad Request.