SQL查询 - 跨多个表进行分组/聚合

时间:2016-11-14 00:00:24

标签: sql-server join subquery aggregate

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

日期表 -

enter image description here

注意:并非所有日期都有电话和销售。

附加表 -

需要完成什么 -

1)通过加入调用表(在agent_no上)和销售(在JDE上)表来加入和聚合Employee的调用和销售

2)由于并非所有日期都包括电话和销售 - 使用日期维度表来确保所有日期都已显示

期望的结果如下所示 -

enter image description here

我写的查询执行 - 我需要很长时间才能取消查询。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

  1. 删除where [skill_name] like '5700 sales l%'
  2. 中的主要通配符
  3. group by放入子查询
  4. 我在这里有一个例子来实现这两个。 (请注意,我做了一些重新格式化,只是为了尝试了解您的查询正在做什么。)

    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];