Similar to this question, I need to group a large number of records into 1-hour "buckets". For example, let's say I've got a typical ORDER table with a datetime attached to each order. And I want to see the total number of orders per hour. So I'm using SQL roughly like this:
SELECT datepart(hh, order_date), SUM(order_id)
FROM ORDERS
GROUP BY datepart(hh, order_date)
The problem is that if there are no orders in a given 1-hour "bucket", no row is emitted into the result set. I'd like the resultset to have a row for each of the 24 hour, but if no orders were made during a particular hour, just record the number of orders as O.
Is there any way to do this in a single query?
See also Getting Hourly Statistics Using SQL.
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `ORDERS` ADD INDEX `orders_idx_datepart_date` (`datepart_hh_order_date`);
SELECT
datepart(hh,
ORDERS.order_date),
SUM(ORDERS.order_id)
FROM
ORDERS
GROUP BY
ORDERS.datepart_hh_order_date
ORDER BY
NULL