Write a SQL query to find the number of orders placed each month. Dataset: CREATE TABLE…
- User
Write a SQL query to find the number of orders placed each month.
Dataset: CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, amount DECIMAL(10, 2), order_date DATE, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) );
INSERT INTO orders (order_id, customer_id, amount, order_date) VALUES (1, 1, 2500, '2023-01-01'), (2, 2, 3000, '2023-01-15'), (3, 1, 1500, '2023-02-03'), (4, 3, 4000, '2023-02-12'), (5, 1, 3000, '2023-02-18'), (6, 2, 4500, '2023-03-01'), (7, 4, 5000, '2023-03-05'), (8, 5, 2000, '2023-03-10');
- Assistant
To find the number of orders placed each month, you need to group the orders by year and month extracted from the
order_datecolumn, then count the orders in each group.Here's a SQL query that does that:
sqlSELECT DATE_FORMAT(order_date, '%Y-%m') AS year_month, COUNT(*) AS num_orders FROM orders GROUP BY year_month ORDER BY year_month;Explanation:
DATE_FORMAT(order_date, '%Y-%m')extracts the year and month as a string inYYYY-MMformat.COUNT(*)counts the total orders in each group.GROUP BY year_monthgroups the orders by year and month.ORDER BY year_monthsorts the output chronologically.
If your SQL engine does not support
DATE_FORMAT(e.g., PostgreSQL), you can use an equivalent like:sql