每小时每天记录记录,在何处/有条款问题

时间:2015-02-18 22:15:30

标签: sql

我有计算HourlyCountPerDay的查询。它工作正常,直到我在st.Occurred上添加Where或Having Clause。 查询是

  SELECT DATEADD(hour, DATEDIFF(hour, 0, st.Occurred), 0) AS DateHourStamp,
  COUNT(*) AS TotalCount,at.[Key] 
  FROM  dbo.SomeTable st INNER JOIN             
  dbo.AnotherTable at ON st.ID = at.ID 
  GROUP BY  DATEADD(hour, DATEDIFF(hour, 0, st.Occurred), 0), at.Key 
  ORDER BY  DateHourStamp DESC

以下是结果

DateHourStamp     TotalCount    Key
2/17/15 14:00 PM     41         A22F0D83-544E-4AE9-B426-D12B2F98E239
2/17/15 14:00 PM     42         DD1E803B-76C9-4D74-8E08-CF36FD074A36
2/17/15 13:00 PM     85         DD1E803B-76C9-4D74-8E08-CF36FD074A36
2/17/15 14:00 PM     54         A22F0D83-544E-4AE9-B426-D12B2F98E239

到目前为止哪个是正确的。现在,只要我在下面添加了Having或Where子句

HAVING (DATEADD(hour, DATEDIFF(hour, 0,st.Occurred), 0) BETWEEN CONVERT(DATETIME, '2015-02-14', 102) AND CONVERT(DATETIME, '2015-02-17', 102) )

它将整个计数数字更改为错误计数,将时间更改为00:00。我花了几个多小时?

有什么想法我做错了吗?我正在使用2008r2,但它必须在2005年工作

2 个答案:

答案 0 :(得分:0)

问题是,除了午夜时分之外,你将失去17日的那一天。

将范围的结尾更改为以下内容:

CONVERT(DATETIME, '2015-02-17 23:00', 102)

答案 1 :(得分:-1)

以下应该有效。注意日期范围。在您的示例中,所有DateHourStamp都是2/17/15。范围直到' 2015-02-17' (对于SQL Server datetime是' 2015-02-17 00:00:00),他们不会被包括在内。为了包括整天2/17/15,范围应该结束' 2015-02-18' (2015-02-18 00:00:00)或2015-02-17 23:59:59(或使用< 2015-02-18)

 SELECT DATEADD(hour, DATEDIFF(hour, 0, st.Occurred), 0) AS DateHourStamp,
      COUNT(*) AS TotalCount,at.[Key] 
      FROM  dbo.SomeTable st INNER JOIN             
      dbo.AnotherTable at ON st.ID = at.ID

    where (DATEADD(hour, DATEDIFF(hour, 0,TL.Occurred), 0) BETWEEN '2015-02-14' AND '2015-02-17'

      GROUP BY  DATEADD(hour, DATEDIFF(hour, 0, st.Occurred), 0), at.Key 
      ORDER BY  DateHourStamp DESC