2017-03-22 77 views
2

我有一個需要修改的查詢。它目前有一個每行15分鐘的時間塊和賬號相關的參考。我的目標是每15分鐘有一行,指出哪個帳號在該塊中最常出現。查找特定組中最常見的值

SELECT 
left(cast(Concat([Hour],':',[Minute]) as time),5) as [Time Block] 
,[Reference] 
,[Account] 

from(

    SELECT 
DATEPART(hh,[Start Time]) as [Hour] 
,[Reference] 
,case when DATEPART(mi,[Start Time]) between 00 and 15 then '00' 
when DATEPART(mi,[Start Time]) between 15 and 30 then '15' 
     when DATEPART(mi,[Start Time]) between 30 and 45 then '30' 
     when DATEPART(mi,[Start Time]) between 45 and 100 then '00' 
     else 'Error' end AS [Minute] 

     ,[Account] 

    FROM [iPR].[dbo].[InboundCallsView] 

    where [Start Time] between '2017-03-21' and '2017-03-22')T 

    order by [Time Block] 

這使輸出

output

我不需要參考數字,但我終究

00:00 310523

00:15 310523

00:30 310523

等等在24小時內顯示每行15分鐘最多行的帳號。這可能嗎?

回答

5

該值在統計學中稱爲模式。這很容易計算:

with cte as (<your query here>) 
select timeblock, account 
from (select timeblock, account, count(*) as cnt, 
      row_number() over (partition by timeblock order by count(*) desc) as seqnum 
     from cte 
     group by timeblock, account 
    ) t 
where seqnum = 1; 

在最常見的情況下,這將返回任意一個值。如果你想要所有這些,然後使用rank()dense_rank()

+0

非常感謝:) – tomdemaine