不按时间间隔SQL Server进行分组

时间:2015-03-31 13:53:07

标签: sql sql-server tsql

我试图按时间间隔(每小时)对结果进行分组我不能为我的生活做出这样的决定。我需要专家来帮助我,有人能看到我哪里出错吗?

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

3 个答案:

答案 0 :(得分: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是包含该列的表的别名。

答案 1 :(得分: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)

答案 2 :(得分: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