2016-11-14 108 views
1
select D.[Date], E.emp_name, E.emp_jde, count(C.[agent_no]) calls, count(S.[EMPJDENUM]) sales 
from 
(select cast([start_date] as date) dte, [agent_no] 
from call_table 
where [skill_name] like '%5700 sales l%' 
and [Agent_Time] != '0' 
) C 
full outer join 
(select [AC#DTE_dt], [EMPJDENUM] 
from sales_table 
where [ICGCD2] in ('LAWN', 'HORT') 
and [CHANNEL]= 'INQ' 
and [ITMQTY]>3 
) S on c.dte=s.[AC#DTE_dt] 
right join 
(select [Date] 
from Date_table 
) D on c.dte=d.[Date] or s.[AC#DTE_dt]=d.[Date] 
right join 
(select [emp_name], [emp_jde], [agent_no] 
from Employee_table 
) E on C.[agent_no]=E.agent_no and S.[EMPJDENUM]=E.emp_jde 
group by D.[Date], E.emp_name, E.emp_jde 

日期表 -SQL查询 - 分组/汇总跨多个表

enter image description here

注:并非所有的日期将同时拥有电话和销售。

附加表 -

有什么需要完成 -

1)加入和总通话和销售由职工通过加入电话表(上agent_no)和销售(在JDE )表

2)由于不是所有的日期都包括呼叫和销售 - 使用日期维度表来确保所有日期都被表示

期望的结果是这样的 -

enter image description here

查询我写的执行 - 它需要很长时间我只是最终取消查询。

任何帮助,将不胜感激。

+0

每个表中大概有多少行? – mendosi

+0

呼叫表将有大约800k,销售表每年大约有400k数据。 – user3067478

+0

您能否包括估计的执行计划请https://www.brentozar.com/pastetheplan/ – mendosi

回答

0

没有看到查询计划,这是一个有点棘手,但这里有可能会提高性能一些建议:

  1. 删除开头的通配符where [skill_name] like '5700 sales l%'
  2. group by到子查询

我在这里有一个例子,实现这两个。 (请注意,我做了一些重新格式化只是为了尝试了解您的查询在做什么。)

select D.[Date], E.emp_name, E.emp_jde, C.Calls, S.Sales 
    from Date_table As D 
    Left Join (
    select cast([start_date] as date) As CallDate, [agent_no], Count(*) As Calls 
     from call_table 
     where [skill_name] like '5700 sales l%' 
     and [Agent_Time] != '0' 
     Group By Cast([start_date] As date), [agent_no]) As C On D.[Date] = C.CallDate 
    Left Join (
    select [AC#DTE_dt] As SaleDate, [EMPJDENUM], Count(*) As Sales 
     from sales_table 
     where [ICGCD2] in ('LAWN', 'HORT') 
     and [CHANNEL]= 'INQ' 
     and [ITMQTY]>3 
     Group By [AC#DTE_dt], [EMPJDENUM]) As S on D.[Date] = s.SaleDate 
    right join Employee_table As E 
    on C.[agent_no]=E.agent_no 
    and S.[EMPJDENUM]=E.emp_jde; 

编辑

为了得到一排日期和员工的每个可能的组合,你会需要日期表和雇员表的交叉连接。

select D.[Date], E.emp_name, E.emp_jde, C.Calls, S.Sales 
    from Date_table As D, 
     Employee_table as E 
    Left Join (
    select cast([start_date] as date) As CallDate, [agent_no], Count(*) As Calls 
     from call_table 
     where [skill_name] like '5700 sales l%' 
     and [Agent_Time] != '0' 
     Group By Cast([start_date] As date), [agent_no]) As C 
    On D.[Date] = C.CallDate 
    And E.agent_no = C.agent_no 
    Left Join (
    select [AC#DTE_dt] As SaleDate, [EMPJDENUM], Count(*) As Sales 
     from sales_table 
     where [ICGCD2] in ('LAWN', 'HORT') 
     and [CHANNEL]= 'INQ' 
     and [ITMQTY]>3 
     Group By [AC#DTE_dt], [EMPJDENUM]) As S 
    on D.[Date] = s.SaleDate 
    and E.emp_jde = S.[EMPJDENUM]; 
+0

这非常接近 - 但是发生的事情是,如果某人没有销售或销售的电话而没有某一天的电话,它是让他们脱离结果。 – user3067478

+0

并且此查询有效地运行。 – user3067478

+0

@ user3067478我做了一些调整,即使在没有销售或电话的情况下也应该返回行 – mendosi