2015-03-31 175 views
0

我試圖按時間間隔(小時)對結果進行分組,我無法爲我的生活弄清楚這一點。我需要專家來幫助我,任何人都可以看到我要出錯的地方嗎?不按時間間隔分組SQL Server

DECLARE @IntervalMinutes AS INT 
SELECT @IntervalMinutes = 60 

SELECT  
     CONVERT(VARCHAR(5),DATEADD(MINUTE,(DATEDIFF(MINUTE,'19000101',dbo.cmp_EEAddLines.CallTime)/@IntervalMinutes) * @IntervalMinutes, '19000101'),108) AS CallTime, 
     COUNT(dbo.Dial.HistoryID) AS TotalDials, 
     SUM(CONVERT(numeric, dbo.CRCTotal.Contact)) AS Contacts, 
     SUM(CONVERT(numeric, dbo.CRCTotal.FinalCRC)) AS Completes 
FROM   
     dbo.cmp_EEAddLines LEFT OUTER JOIN 
     dbo.Dial ON 
     dbo.cmp_EEAddLines.DialID = dbo.Dial.DialID LEFT OUTER JOIN 
     dbo.CRCTotal ON 
     dbo.Dial.CRC = dbo.CRCTotal.CRC 
WHERE 
     (dbo.cmp_EEAddLines.CallDate >= 29/03/2015) 
GROUP BY 
     CallTime 

回答

2

你可以打破每個要日期部分:

select year(e.cmp_EEAddLines.CallTime), month(e.cmp_EEAddLines.CallTime), 
     day(e.cmp_EEAddLines.CallTime), 
     datepart(hour, cmp_EEAddLines.CallTime), 
     . . . 
group by year(e.cmp_EEAddLines.CallTime), month(e.cmp_EEAddLines.CallTime), 
     day(e.cmp_EEAddLines.CallTime), 
     datepart(hour, cmp_EEAddLines.CallTime) 

這不會形成最終的輸出爲datetime,但它可能對你的工作需要。

注意:e是帶列的表的別名。

0

以下是按年/月/日/小時製作「點擊次數」列表的一種方法。

  • 只有存在幾個小時纔有活動的行 - 也就是說,會有間隙。
  • 基於這些外部連接,你可以有TotalDials沒有任何ContactsCompletes
  • 結果列表中不包含一個日期時間值。如果需要,可以通過將其作爲子查詢並將日期組件「拼接」回日期時間來添加。

代碼:

SELECT 
    datepart(yy, al.CallTime) Year 
    ,datepart(mm, al.CallTime) Month 
    ,datepart(dd, al.CallTime) Day 
    ,datepart(hh, al.CallTime) Hour 
    ,COUNT(di.HistoryID)    TotalDials 
    ,SUM(CONVERT(numeric, cr.Contact)) Contacts 
    ,SUM(CONVERT(numeric, cr.FinalCRC)) Completes 
FROM   
    dbo.cmp_EEAddLines al 
    INNER JOIN dbo.Dial di -- Left join to inner; counts and sums are identical, query will be faster 
     ON al.DialID = di.DialID 
    LEFT OUTER JOIN dbo.CRCTotal cr 
     ON di.CRC = cr.CRC 
group by 
    datepart(yy, al.CallTime) -- Year 
    ,datepart(mm, al.CallTime) -- Month 
    ,datepart(dd, al.CallTime) -- Day 
    ,datepart(hh, al.CallTime) -- Hour 
order by 
    datepart(yy, al.CallTime) -- Year 
    ,datepart(mm, al.CallTime) -- Month 
    ,datepart(dd, al.CallTime) -- Day 
    ,datepart(hh, al.CallTime) -- Hour 
1

每個人似乎每個日期時間被分解成各個部分時,在現實中,你只需要兩個部分。日期和小時。試試這個:

SELECT CAST(dbo.cmp_EEAddLines.CallTime AS DATE) as dates, 
     DATEPART(HOUR,dbo.cmp_EEAddLines.CallTime) AS hr 
... 

GROUP BY CAST(dbo.cmp_EEAddLines.CallTime AS DATE), 
      DATEPART(HOUR,dbo.cmp_EEAddLines.CallTime) 

如果你想在一列中,你可以試試這個。它會將每個日期時間值四捨五入到最近的小時。

SELECT CAST(CONCAT(CAST(dbo.cmp_EEAddLines.CallTime AS DATE),' ',DATEPART(HOUR,dbo.cmp_EEAddLines.CallTime),':00:00.000') AS DATETIME) 

.... 

GROUP BY CAST(CONCAT(CAST(dbo.cmp_EEAddLines.CallTime AS DATE),' ',DATEPART(HOUR,dbo.cmp_EEAddLines.CallTime),':00:00.000') AS DATETIME)