【问题标题】:SQL Server Query - Missing DataSQL Server 查询 - 缺少数据
【发布时间】:2017-03-29 22:41:56
【问题描述】:

我遇到了从查询结果中排除数据的问题 -

select 
    D.[Date], D.MonthName, D.WeekOfYear, 
    E.bu_name, E.emp_mgr, E.emp_sup, E.emp_name, E.emp_jde, 
    C.Calls, S.sales
from 
    DATE TABLE As D
join 
    (Select 
         cast([start_date] as date) as call_date, [agent_no], 
         sum(case when [skill_name] like '5700 Sales l%' and [Agent_Time] != '0' then 1 else 0 end) as calls
     from 
         CALL TABLE
     group by 
         cast([start_date] as date), [agent_no]) As C on D.[Date] = C.call_date
join 
    (Select 
         [AC#DTE_dt] As sale_date, [EMPJDENUM], 
         sum(case when [CH]='I' and ([IC]='L' or [IC]='H') and [ITMQTY]>3 and [EMPBUNCOD] in ('5044', '5077', '5169', '5178', '5179', '5186', '5187', '5189', '5190') then 1 else 0 end) as sales
     from 
         SALE TABLE
     group by 
         [AC#DTE_dt], [EMPJDENUM]) As S on D.Date = s.sale_date
join 
    EMPLOYEE TABLE As E on C.[agent_no] = E.[emp_vcc]
                        and S.[EMPJDENUM] = E.emp_jde
                        and S.sale_date between E.start_date and E.end_date
where 
    D.[Date] = '11/5/2016'

结果

如果 call 或 sales 子查询表都与查询底部 Employee 表的连接中定义的 employees 表匹配 - 从 sum(case when 将返回。如果出于任何原因, call 或 sales 子查询中没有要加入的数据,该行被排除在外。我想要的是结果返回 0 或 null。

有什么想法吗?

【问题讨论】:

    标签: sql-server tsql subquery case aggregate


    【解决方案1】:

    您似乎只需要指定何时有 OUTER 连接,以及您在哪里进行 INNER 连接

    select 
        D.[Date], D.MonthName, D.WeekOfYear, 
        E.bu_name, E.emp_mgr, E.emp_sup, E.emp_name, E.emp_jde, 
        C.Calls, S.sales
        from 
        DATE TABLE As D
    LEFT OUTER join 
        (Select 
         cast([start_date] as date) as call_date, [agent_no], 
         sum(case when [skill_name] like '5700 Sales l%' and [Agent_Time] != '0' then 1 else 0 end) as calls
     from 
         CALL TABLE
     group by 
         cast([start_date] as date), [agent_no]) As C on D.[Date] = C.call_date
    LEFT OUTER join 
        (Select 
         [AC#DTE_dt] As sale_date, [EMPJDENUM], 
         sum(case when [CH]='I' and ([IC]='L' or [IC]='H') and [ITMQTY]>3 and [EMPBUNCOD] in ('5044', '5077', '5169', '5178', '5179', '5186', '5187', '5189', '5190') then 1 else 0 end) as sales
     from 
         SALE TABLE
     group by 
         [AC#DTE_dt], [EMPJDENUM]) As S on D.Date = s.sale_date
    INNER join 
    EMPLOYEE TABLE As E on C.[agent_no] = E.[emp_vcc]
                        and S.[EMPJDENUM] = E.emp_jde
                        and S.sale_date between E.start_date and E.end_date
    where 
    D.[Date] = '11/5/2016'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多