2017-03-24 133 views
1

使用SQL Server 2014.我有一個記錄的時間戳列表,我想要記錄每個記錄的記錄數然後每天30分鐘的記錄數超過了規定的數量多少小時算,說20SQL計算每小時記錄數並計算總記錄數大於值的小時數

這是我到目前爲止有:

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不正確嗎?任何意見,將不勝感激!

+1

你不應該按小時分組來計算,不計算有多少小時? – TZHX

+0

我沒有按小時分組,因爲我想知道有多少小時符合我的標準。那麼對於每一天,總數超過限制的時間有多少?如果我按小時分組,我會得到一個已經結束的小時數列表,但不是按天計算的。 –

回答

0

你有種這裏有2個部分的問題

我想看看有多少紀錄每小時有

您可以創建一個返回的元組查詢(RecordsPerHour,HOUR ,年,月,日)如下:

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