2016-09-06 107 views
0

我想從兩個子查詢中減去結果,但我想返回多於1行,因爲我想查看總調用以及它們在特定日期範圍內的差異,下面的代碼會給我一個錯誤:「子查詢返回的值超過1個值,當子查詢跟隨=,!=,<,<,< =,>,> =或當子查詢用作表達式「。希望你能幫助我。請注意,這是存儲過程的一部分。先謝謝你。減去返回多於1行的兩個SQL子查詢的結果

SELECT distinct 

c.reporting as 'Agent_ID' 
,count(a.pkey) as 'Total_Calls_Handled' 
,a.MidnightStartDate as 'Call_Start_Time' 
,datename(dw,a.midnightstartdate) as 'Week_day' 
,a.[queue] 

into #temp3 
FROM t1 a 
join t2 b 
on a.FKAgent = b.fkagent 
join t3 c 
on a.agent = c.reporting 
where a.agent in (

    '132568' 
,'116308' 
,'132083' 
,'113737' 

) 

and convert(date, midnightstartdate) BETWEEN '08/29/16' AND '08/30/19' 
group by c.Reporting,a.MidnightStartDate,a.[queue] 


SELECT distinct b.[Week_Day], a.[Queue],[Total ACD Calls], [Total ACD Calls Handled], count([total_calls_handled]) as 'Total ACD Calls Handledby Agent', 

(select ((select [total acd calls handled] from #temp2) - 
(select count([total_calls_handled]) from #temp3))) as 'OperatorsCalls' 

INTO #Temp4 
FROM #Temp2 a 
JOIN #Temp3 b 
ON a.[Queue] = b.[Queue] 
GROUP BY [Total ACD Calls], [Total ACD Calls Handled], b.[Week_Day] , a.[Queue],[total_calls_handled] 
+0

你#TEMP2表可能包含的結果多行,而你在可以返回只有一個值的單個記錄的上下文使用選擇就可以了。 –

+0

是的,它有多行。如果日期範圍只有1天,上面的代碼可以正常工作。但我希望看到整個一週的差異讓我們說。有什麼方法可以做到嗎? – Emarie

回答

0

這是我最好的一擊,它沒有一個工作的SQL小提琴,所以如果它不是現貨道歉。基本上,您需要在加載數據之前創建臨時表,執行計算(然後可以保持多行格式),然後將其加入最終的#temp4表中的最終插入。

SELECT distinct 

c.reporting as 'Agent_ID' 
,count(a.pkey) as 'Total_Calls_Handled' 
,a.MidnightStartDate as 'Call_Start_Time' 
,datename(dw,a.midnightstartdate) as 'Week_day' 
,a.[queue] 

into #temp3 
FROM t1 a 
join t2 b 
on a.FKAgent = b.fkagent 
join t3 c 
on a.agent = c.reporting 
where a.agent in (

'132568' 
,'116308' 
,'132083' 
,'113737' 

) 

and convert(date, midnightstartdate) BETWEEN '08/29/16' AND '08/30/19' 
group by c.Reporting,a.MidnightStartDate,a.[queue] 

--new temp table to load temp3 counts 
SELECT 
    Count(total_calls_handled) as total_calls_handled_count, 
    queue 
INTO #Temp3Counts 
FROM 
    #temp3 
GROUP BY queue, total_calls_handled 

-- new temp table to handled subquery calculations 
SELECT 
    T2.Queue, 
    (T2.[Total acd calls handled]-T3.total_calls_handled_count) as  'OperatorsCalls' 
INTO #temp2Calc 
FROM 
    #temp2 as T2 
INNER JOIN 
#temp3Counts as T3 
ON T2.Queue = T3.Queue 

GROUP BY T2.Queue,T2.[Total acd calls handled],T3.total_calls_handled_count 



SELECT distinct b.[Week_Day], a.[Queue],[Total ACD Calls], [Total ACD Calls  Handled], count([total_calls_handled]) as 'Total ACD Calls Handledby Agent',  T2C.OperatorsCalls 

INTO #Temp4 
FROM #Temp2 a 
JOIN #Temp3 b 
ON a.[Queue] = b.[Queue] 
INNER JOIN 
    #Temp2Calc as T2C 
ON T2C.queue = a.queue 
GROUP BY b.[Week_Day], a.queue,[Total ACD Calls],[Total ACD Calls Handled], [total_calls_handled],T2C.OperatorsCalls 
+0

謝謝。有效。 – Emarie

+0

如果你可以將它標記爲答案,它可以幫助未來搜索潛在的人:) – Zi0n1

+0

我剛剛做到了。謝謝你提醒我。 :) – Emarie