2017-06-15 43 views
-1

我從具有25列標題的百萬行表中提取數據。我有一個簡單的查詢,可以根據日期提取總的應答呼叫和總連接秒數。SQL Server - 根據前300行(和301+)總結列

SELECT 
convert(date,format(Dateadd(hh,1,[Start Time]),'dd/MM/yyyy'),103) as [Date] 
,sum(iif([type] = 'normal operator call',1,0)) as [answered calls] 
,sum([connected (secs)]) as [total con sec] 


from inboundcallsview 

where [account] = '106844' 

and dateadd(hh,1,[start time]) between '2017-05-01' and '2017-06-01' 

group by convert(date,format(Dateadd(hh,1,[Start Time]),'dd/MM/yyyy'),103) 

我所希望做的是和第一個300的連接秒(按[開始時間]列)接聽的電話(任一行其中[類型] =「普通話務員呼叫」)的各日(由[日期]欄定義)。以及從301開始的所有呼叫的總連接秒數。基本上我的電流輸出爲

current

,我想它是

desired output

忽略日期的變化六月(06)應可(05)我搞砸了創建我例。我最終會想要在所有日期這樣做,所以日期參數並不重要。

在此先感謝。

+0

你知道ROW_NUMBER函數? –

+0

我知道它存在,但不知道如何將它合併,當我已經分裂和按日期分組,並且每個日期的行數將是隨機的。這就是我想要的幫助。有沒有辦法讓每個日期都是自己的子表,並計算該子表的行數?那將是什麼樣子? – tomdemaine

+0

用'OVER(PARTITION BY(你的日期輸出)ORDER BY [開始時間])研究'ROW_NUMBER''順便說一句,你將不得不UNION兩個派生表。一桌1-300,另一桌301+ –

回答

1

在僞代碼,它看起來就像這樣:

WITH CTE AS (
    SELECT {Your Date Output} AS [date], 
     ,[ConnectedSecs] 
     ROW_NUMBER() OVER (PARTITION BY {Your Date Output}, ORDER BY [Start Time]) AS rn 
    FROM YourTable 
    WHERE {Conditions} 
) 
SELECT 
    [date], 
    'First 300' AS Bracket, 
    SUM(ConnectedSecs) 
    FROM CTE WHERE rn < 301 
    GROUP BY [date] 
UNION ALL SELECT 
    [date], 
    '301+' AS Bracket, 
    SUM(ConnectedSecs) 
    FROM CTE WHERE rn >= 301 
    GROUP BY [date] 
ORDER BY [date],{a case expression to have 'First 300' on top if desired} 
+0

這是非常有用的,謝謝! – tomdemaine