Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count rows per hour in SQL Server with full date-time value as result

Tags:

How can I count the number of rows per hour in SQL Server with full date-time as result.

I've already tried this, but it returns only the hours

SELECT DATEPART(HOUR,TimeStamp), Count(*)
FROM [TEST].[dbo].[data]
GROUP BY DATEPART(HOUR,TimeStamp)
ORDER BY DATEPART(HOUR,TimeStamp)

Now the result is:

Hour   Occurrence 
----   ----------
10     2157
11     60740
12     66189
13     77096
14     90039

But I need this:

Timestamp               Occurrence
-------------------     ----------
2013-12-21 10:00:00     2157
2013-12-21 11:00:00     60740
2013-12-21 12:00:00     66189
2013-12-21 13:00:00     77096
2013-12-21 14:00:00     90039
2013-12-22 09:00:00     84838
2013-12-22 10:00:00     64238
like image 323
John Doe Avatar asked Dec 21 '13 14:12

John Doe


People also ask

How do I get hourly count in SQL Server?

Here is the SQL query to get data for every hour in MySQL. In the above query, we simply group by order_date using HOUR function and aggregate amount column using SUM function. HOUR function retrieves hour number from a given date/time/datetime value, which can be provided as a literal string or column name.

How do I count rows in SQL Server?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

How do I count rows of data in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do I get SQL hourly data?

MySQL HOUR() Function The HOUR() function returns the hour part for a given date (from 0 to 838).


1 Answers

You actually need to round the TimeStamp to the hour. In SQL Server, this is a bit ugly, but easy to do:

SELECT dateadd(hour, datediff(hour, 0, TimeStamp), 0) as TimeStampHour, Count(*)
FROM [TEST].[dbo].[data]
GROUP BY dateadd(hour, datediff(hour, 0, TimeStamp), 0)
ORDER BY dateadd(hour, datediff(hour, 0, TimeStamp), 0);
like image 79
Gordon Linoff Avatar answered Oct 17 '22 05:10

Gordon Linoff