SQL JOIN加倍值

时间:2016-07-06 10:42:52

标签: sql sql-server join group-by ssms

我有两个带有以下数据的临时表:

temp_aht

enter image description here

TEMP_1

enter image description here

我使用此查询连接事件列上的两个表:

    Select 
       count(distinct a.Incident) as nr_of_tickets 
      ,a.[Service]
      ,SUM(CASE WHEN a.status_switch  IN ('Assigned » In Progress','Assigned » Pending','Assigned » Resolved','Assigned » Closed') THEN a.TotalSeconds ELSE NULL END) AS AssignedTime
      ,SUM(CASE WHEN a.status_switch  IN ('In Progress » Assigned','In Progress » Assigned','In Progress » Pending','In Progress » Resolved') THEN a.TotalSeconds ELSE NULL END) AS ProgressTime
      ,SUM(CASE WHEN a.status_switch  IN ('Pending » Assigned','Pending » In Progress') THEN a.TotalSeconds ELSE NULL END) AS PendingTime
      ,sum(b.Creation) as Creation
      ,sum(b.[Call duration]) as [Call duration] 
 from ##temp_aht as a inner join ##temp_1 as b on a.incident = b.incident_id
 group by a.[Service],b.Creation,b.[Call duration]

如果我使用上述查询加入表格,则SUMs不会正确。 我认为这是因为在两个表中我都有多个具有相同事件ID的行。

但是,如果找到匹配项,我怎样才能加入表格并只从## temp_1开始第一行?

1 个答案:

答案 0 :(得分:2)

问题是两个表中的每个事件都有多行。由于您正在加入一个列(事件),然后由另一个列(服务)聚合,这一事实变得更加复杂。

然后,您的group by包含b表格中的汇总列,这是没有意义的。

解决方案是在进行连接之前聚合两个表。我想这就是你想要的:

select sum(nr_of_tickets), a.[Service],
       sum(AssignedTime) as AssignedTime,
       sum(ProgressTime) as ProgressTime,
       sum(PendingTime) as PendingTime,
       sum(b.Creation) as Creation,
       sum(b.[Call duration]) as [Call duration] 
from (select a.Service, count(distinct a.Incident) as nr_of_tickets,
             SUM(CASE WHEN a.status_switch  IN ('Assigned » In Progress','Assigned » Pending','Assigned » Resolved','Assigned » Closed') THEN a.TotalSeconds END) AS AssignedTime
             SUM(CASE WHEN a.status_switch  IN ('In Progress » Assigned','In Progress » Assigned','In Progress » Pending','In Progress » Resolved') THEN a.TotalSeconds END) AS ProgressTime,
             SUM(CASE WHEN a.status_switch  IN ('Pending » Assigned','Pending » In Progress') THEN a.TotalSeconds END) AS PendingTime
      from ##temp_aht a
      group by a.Incident, a.Service
     ) a inner join
     (select b.incident, 
             sum(b.Creation) as Creation,
             sum(b.[Call duration]) as [Call duration]
      from ##temp_1 b
      group by b.incident
     ) b
     on a.incident = b.incident_id
group by a.[Service]