简体   繁体   中英

Count number of occurrences by the hour in SQL

I've tried searching but there doesn't seem to be an answer. Maybe I am googling wrong so I apologize, but basically for a table I need to count the number of rows that have a LogType of success, and group them hour by hour for a certain day... 1/27 for example.

So far I have this

SELECT dateadd(hour, datediff(hour, 0, LogTime), 0) as Hour, LogType
  FROM [<production_db_name>].[dbo].[GPExportLog]
  where LogType like 'Success' and (LogTime BETWEEN '2021-01-27' and '2021-01-28')

Which produces a result that looks like this,

Hour, LogType

3-24-2021 17:00 Success
3-24-2021 17:00 Success
3-24-2021 17:00 Success
3-24-2021 18:00 Success

However, I need it to look something more like this,

hour, count
3-24-2021 17:00, 3
3-24-2021 18:00, 1

Just group by your calculated Hour column?

SELECT DATEADD(HOUR, DATEDIFF(HOUR, 0, LogTime), 0) AS [Hour], COUNT(*) AS [Count]
FROM GPExportLog
WHERE LogType like 'Success' AND (LogTime BETWEEN '2021-01-27' AND '2021-01-28')
GROUP BY DATEADD(hour, DATEDIFF(HOUR, 0, LogTime), 0);

Or cross apply to avoid repeating the calculation

SELECT X.[Hour], COUNT(*) AS [Count]
FROM GPExportLog
CROSS APPLY (VALUES (DATEADD(HOUR, DATEDIFF(HOUR, 0, LogTime), 0))) AS X ([Hour])
WHERE LogType like 'Success' AND (LogTime BETWEEN '2021-01-27' AND '2021-01-28')
GROUP BY X.[Hour];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM