SQL用于计算每小时的记录数,并计算总记录数大于一个值的小时数

时间:2017-03-24 14:28:50

标签: sql sql-server

使用SQL Server 2014.我有一个带有时间戳的记录列表,我想计算每小时有多少记录,然后计算每天记录计数超过给定数量的小时数,比如20。

这是我到目前为止所拥有的:

select count(distinct datepart(hour, convert(datetime, OrderStateDate))) Count_HoursOver,
    datepart(YEAR, convert(datetime, OrderStateDate)) Date_YEAR,
    datepart(month, convert(datetime, OrderStateDate)) Date_MONTH,
    datepart(day, convert(datetime, OrderStateDate)) Date_DAY
from Reporting.dbo.Orders
group by datepart(YEAR, convert(datetime, OrderStateDate)),
    datepart(month, convert(datetime, OrderStateDate)),
    datepart(day, convert(datetime, OrderStateDate))
having count(idscript) >= 20

结果不正确,我无法理解返回的内容和原因。我不正确地使用HAVING吗?任何建议将不胜感激!

2 个答案:

答案 0 :(得分:0)

你在这里有两个部分的问题

  

我想计算每小时有多少记录

您可以创建一个返回元组(RecordsPerHour,HOUR,YEAR,MONTH,DAY)的查询,如下所示:

SELECT 
    count(*) as RecordsPerHour, 
    datepart(hour,convert(datetime,OrderStateDate)) as Date_HOUR, 
    datepart(year,convert(datetime,OrderStateDate)) as Date_YEAR,
    datepart(month,convert(datetime,OrderStateDate)) as Date_MONTH,
    datepart(day,convert(datetime,OrderStateDate)) as Date_DAY
FROM Reporting.dbo.Orders
GROUP BY
    datepart(year,convert(datetime,OrderStateDate)),
    datepart(month,convert(datetime,OrderStateDate)),
    datepart(day,convert(datetime,OrderStateDate)),
    datepart(hour,convert(datetime,OrderStateDate))
  

然后计算每天记录计数超过给定数量的小时数,比如20

要执行此操作,请在嵌套查询中使用问题第一部分中的查询,使用HAVING子句仅过滤包含至少20个订单的小时数。

在外部查询上,按(年,月,日)分组以确定当天至少有20个订单的小时数:

SELECT
    count(*) as HoursWithAtLeast20Orders, 
    Date_YEAR,
    Date_MONTH,
    Date_DAY
FROM
    (SELECT 
        datepart(hour,convert(datetime,OrderStateDate)) as Date_HOUR, 
        datepart(year,convert(datetime,OrderStateDate)) as Date_YEAR,
        datepart(month,convert(datetime,OrderStateDate)) as Date_MONTH,
        datepart(day,convert(datetime,OrderStateDate)) as Date_DAY
    FROM Reporting.dbo.Orders
    GROUP BY
        datepart(year,convert(datetime,OrderStateDate)),
        datepart(month,convert(datetime,OrderStateDate)),
        datepart(day,convert(datetime,OrderStateDate)),
        datepart(hour,convert(datetime,OrderStateDate))
    HAVING count(*) >=20) as t
GROUP BY
    Date_YEAR,
    Date_MONTH,
    Date_DAY

答案 1 :(得分:0)

第一轮到第一轮,然后是第二轮

SELECT 
   count(*) as [hours with 20+ Orders],
   dateadd(day, datediff(day,'20000101',dt_hour_rounded),'20000101') as dt_day_rounded     
FROM (
   SELECT
      count(*) as OrdersInHour,
      dateadd(hour, datediff(hour,'20000101',OrderStateDate),'20000101') as dt_hour_rounded
   FROM Reporting.dbo.Orders
   GROUP BY dateadd(hour, datediff(hour,'20000101',OrderStateDate),'20000101')
) t
GROUP BY dateadd(day,datediff(day,'20000101',dt_hour_rounded),'20000101')
WHERE OrdersInHour >= 20