Sql-server – Grouping count by interval of 15 minutes

sql-server-2008-r2sql-server-2012

I was trying to write a query where I can group the data by 15 minutes interval.

Example:

Table1

I want to count the orders by interval.
So Output should be:

Output

How can this be written?

Best Answer

If you can deal with not counting zeros, you can avoid a calendar table

SELECT 
    DATEADD(MINUTE, (DATEDIFF(MINUTE, '20000101', TransactionDate) / 15)*15, '20000101'),
    count(*)
FROM 
    Transactions
GROUP BY
    DATEADD(MINUTE, (DATEDIFF(MINUTE, '20000101', TransactionDate) / 15)*15, '20000101')

gives

2017-07-10 11:30:00.000 2
2017-07-10 11:45:00.000 1
2017-07-10 12:00:00.000 5
2017-07-10 12:15:00.000 1