Reputation: 425
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
Upvotes: 0
Views: 1182
Reputation: 27225
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];
Upvotes: 3