YA__XIN 2021-10-21 04:57 采纳率: 0%
浏览 33

oracle统计一对多表,怎么用一条sql查询


select  COUNT(distinct cs.id),COUNT(distinct fo.id),COUNT(distinct re.id),COUNT(distinct lo.id) from dh_project_saler ps
left join dh_crm_saleruser cs
on cs.saleropenid=ps.saleropenid
left join dh_crm_follow fo
on fo.saler_openid=ps.saleropenid
left join dh_crm_record re
on re.saler_open_id=ps.saleropenid
left join dh_crm_look lo
on lo.saler_openid=ps.saleropenid

where cs.createtime between '2021-09-26' and '2021-09-27' 
            and fo.operating_time between '2021-09-26' and '2021-09-27'
            and re.operating_time between '2021-09-26' and '2021-09-27'
            and lo.create_time between '2021-09-26' and '2021-09-27'
            and ps.number='HJ000069'

当这样子去查询的时候,如果最后一个统计为0的时候,前面的所有count都等于0了,怎么解决啊

  • 写回答

3条回答 默认 最新

  • CSDN专家-文盲老顾 2021-10-21 09:42
    关注

    首先,当 lo 没有与之匹配的数据时,count(lo.id) 为 0,那么,也就是说 lo.create_time 所有值都为 null,所以 lo.create_time between 的结果就是,没有任意行符合条件,从结构上来说,你的条件定义存在逻辑性问题

    我用 mssql 写个类似的,你可以参考下

    declare @bdate date,@edate date
    
    select @bdate = '2021-09-26',@edate='2021-09-27'
    
    select  COUNT(distinct cs_id)
        ,COUNT(distinct fo_id)
        ,COUNT(distinct re_id)
        ,COUNT(distinct lo_id) 
    from (
        select  (case when cs.createtime between @bdate and @edate then cs.id else null end) as cs_id
            ,(case when fo.operating_time between @bdate and @edate then fo.id else null end) as fo_id
            ,(case when re.operating_time between @bdate and @edate then re.id else null end) as re_id
            ,(case when lo.createtime between @bdate and @edate then lo.id else null end) as lo_id
        from dh_project_saler ps
        left join dh_crm_saleruser cs on cs.saleropenid=ps.saleropenid
        left join dh_crm_follow fo on fo.saler_openid=ps.saleropenid
        left join dh_crm_record re on re.saler_open_id=ps.saleropenid
        left join dh_crm_look lo on lo.saler_openid=ps.saleropenid
        where ps.number='HJ000069'
    ) a
    
    
    

    即:不管是否有关联数据,都不放到 where 中,而是用 case 进行判断,是否保留该行 id,在外层对所有保留的id进行统计

    如有帮助,还望采纳

    评论

报告相同问题?

问题事件

  • 创建了问题 10月21日

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算