SQL查询中的SUM - 左外连接

时间:2013-03-20 21:31:20

标签: sql sql-server function sum aggregate-functions

以下是场景:

表:

**CallMain:**

Call_ID = PK (INT)
Abandoned (INT) Either 1 or NULL


**CallHold:**

Hold_ID = PK (INT)

Call_ID = FK (INT)

StartTime (INT)

EndTime (INT)

CallMain表中保存的每个调用都可以包含1,0或许多保留记录。每次呼叫保持时,FK都会创建一个记录,其中包含保持的开始时间和保持的结束时间。

现在,要在查询中返回此信息以显示调用及其总保持时间,我相信SQL如下:

SELECT CallMain.Call_ID, CallMain.Abandoned,  
ISNULL((CallHold.EndTime - CallHold.StartTime),0) AS HoldPeriodSeconds 
FROM CTIStatCall 
LEFT OUTER JOIN CallHold ON CallMain.Call_ID = CallHold.Call_ID

此查询应返回没有与之关联的保留记录的调用记录,并应将其作为NULLS返回。具有单个保留记录的呼叫正确显示。 LEFT OUTER JOIN返回的NULLS正在使用ISNULL()函数进行管理,并被替换为零,因为调用没有保持时间。

我的问题是,如果一个呼叫有多个保持记录,它将在结果中出现两次,即:

Call_ID, HoldPeriod

212, 254

213, 154

214, 158

214, 25

214, 10

从上面可以看出,Call 214有多个保持记录,总计为193.如何在查询中添加它,这样它才会显示该调用的总保持期,而不是在结果中多次重复调用记录?

解决方案

SELECT CallMain.Call_ID, CallMain.Abandoned,
 sum(ISNULL((CallHold.EndTime - CallHold.StartTime),0)) AS HoldPeriodSeconds FROM CTIStatCall LEFT OUTER JOIN CallHold ON CallMain.Call_ID = CallHold.Call_ID group by CallMain.Call_ID, CallMain.Abandoned

@AshReva - 这是代码

SELECT CallMain.Call_ID, dateadd(s,CallMain.StartTime, '1970-01-01') AS StartTime,
dateadd(s,CallMain.AnsTime, '1970-01-01') AS AnsTime, 
dateadd(s,CallMain.EndTime, '1970-01-01') AS EndTime,
CallMain.Abandoned,
(CallMain.AnsTime - CallMain.StartTime) AS RingPeriod,
SUM(ISNULL((CallHold.EndTime - CallHold.StartTime),0)) AS HoldPeriod,
(CallMain.EndTime - CallMain.AnsTime) - ISNULL((CallHold.EndTime - CallHold.StartTime),0) AS TalkPeriod
FROM CallMain
LEFT OUTER JOIN
CallHold ON CallMain.Call_ID = CallHold.Call_ID
   GROUP BY CallMain.Call_ID, CallMain.Abandoned, CallMain.StartTime, CallMain.EndTime, CallMain.AnsTime, CallHold.EndTime, CallHold.StartTime
order by CallMain.Call_ID

3 个答案:

答案 0 :(得分:1)

只需使用sum和group by子句。看看下面是否有效。

SELECT 
    CallMain.Call_ID, 
    CallMain.Abandoned,  
    sum(ISNULL((CallHold.EndTime - CallHold.StartTime),0)) AS HoldPeriodSeconds 
FROM CTIStatCall 
LEFT OUTER JOIN CallHold 
   ON CallMain.Call_ID = CallHold.Call_ID
group by CallMain.Call_ID, CallMain.Abandoned

答案 1 :(得分:0)

使用sql sum()函数和group by子句。

SELECT CallMain.Call_ID, CallMain.Abandoned,  
sum(ISNULL((CallHold.EndTime - CallHold.StartTime),0)) AS HoldPeriodSeconds 
FROM CTIStatCall 
LEFT OUTER JOIN CallHold ON CallMain.Call_ID = CallHold.Call_ID
group by CallMain.Call_ID, CallMain.Abandoned

答案 2 :(得分:0)

SELECT
    CallMain.Call_ID,
    CallMain.Abandoned,  
    Sum(ISNULL((CallHold.EndTime - CallHold.StartTime), 0)) AS HoldPeriodSeconds 
FROM
    CallMain
LEFT OUTER JOIN
    CallHold
ON
    CallMain.Call_ID = CallHold.Call_ID
GROUP BY
    CallMain.Call_ID,
    CallMain.Abandoned