CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
courier_id INT,
seller_id INT,
order_timestamp_utc DATETIME,
amount FLOAT,
city_id INT
);
INSERT INTO orders (id, customer_id, courier_id, seller_id, order_timestamp_utc, amount, city_id)
VALUES
(1, 101, 201, 301, '2023-01-15 10:30:00', 50.00, 401),
(2, 102, 202, 302, '2023-01-16 11:45:00', 75.50, 402),
(3, 103, 203, 303, '2023-01-17 12:15:00', 120.25, 403),
(4, 104, 204, 304, '2023-01-18 09:00:00', 30.75, 404),
(5, 105, 205, 305, '2023-01-19 14:20:00', 90.80, 405);
Q.1 Which hour has the highest average order volume per day? Your output should have the hour which satisfies that condition, and average order volume.
Approach 1: With CTE
WITH RankedHours AS ( SELECT DATEPART(HOUR, order_timestamp_utc) AS hour_of_day, AVG(amount) AS average_order_volume, RANK() OVER (ORDER BY AVG(amount) DESC) AS ranking FROM postmates_orders GROUP BY DATEPART(HOUR, order_timestamp_utc) ) SELECT hour_of_day, average_order_volume
FROM RankedHours WHERE ranking = 1; Approach 2: Without CTE which is Select and From SELECT hour_of_day, average_order_volume FROM ( SELECT DATEPART(HOUR, order_timestamp_utc) AS hour_of_day, AVG(amount) AS average_order_volume, RANK() OVER (ORDER BY AVG(amount) DESC) AS ranking FROM postmates_orders GROUP BY DATEPART(HOUR, order_timestamp_utc) ) Y WHERE ranking = 1; Approach 3: Using the Top approach SELECT DATEPART(HOUR, order_timestamp_utc) AS hour_of_day, AVG(amount) AS average_order_volume FROM postmates_orders GROUP BY DATEPART(HOUR, order_timestamp_utc) HAVING AVG(amount) = ( SELECT TOP 1 AVG(amount) FROM postmates_orders GROUP BY DATEPART(HOUR, order_timestamp_utc) ORDER BY AVG(amount) DESC);
Let's break the the third approach and see how it has been done
First Step: Selecting Hourly Averages
SELECT DATEPART(HOUR, order_timestamp_utc) AS hour_of_day, AVG(amount) AS average_order_volume FROM postmates_orders GROUP BY DATEPART(HOUR, order_timestamp_utc);
Second Step: Subquery to Find Highest Average:
SELECT TOP 1 AVG(amount) FROM postmates_orders GROUP BY DATEPART(HOUR, order_timestamp_utc) ORDER BY AVG(amount) DESC;
Third Step: Main Query with HAVING Clause:
SELECT DATEPART(HOUR, order_timestamp_utc) AS hour_of_day, AVG(amount) AS average_order_volume FROM postmates_orders GROUP BY DATEPART(HOUR, order_timestamp_utc) HAVING AVG(amount) = (Subquery Result);
Link of the Question - https://platform.stratascratch.com/coding/2014-hour-with-the-highest-order-volume?code_type=5
Comments
Post a Comment