๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ:
You have 2 minutes to solve this SQL query.
Find the month with the highest total sales.
Assume the table structure: sales(sale_id, sale_date, amount)
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
EXTRACT(YEAR FROM sale_date) AS year,
EXTRACT(MONTH FROM sale_date) AS month,
SUM(amount) AS total_sales
FROM sales
GROUP BY
EXTRACT(YEAR FROM sale_date),
EXTRACT(MONTH FROM sale_date)
ORDER BY total_sales DESC
LIMIT 1;
๐ก Explanation:
This query groups sales by year and month, calculates the total sales for each month, and returns the month with the highest sales.
Key parts:
โข EXTRACT YEAR FROM sale_date gets the year.
โข EXTRACT MONTH FROM sale_date gets the month.
โข SUM amount calculates total monthly sales.
โข ORDER BY total_sales DESC sorts from highest to lowest.
โข LIMIT 1 returns the top-performing month.
This question tests your understanding of:
Date Functions, Aggregate Functions SUM, GROUP BY, ORDER BY
๐ฏ Expected Output Example
Year: 2026, Month: 5, Total Sales: 245,000
๐ Alternative Handles Ties
SELECT
year,
month,
total_sales
FROM (
SELECT
EXTRACT(YEAR FROM sale_date) AS year,
EXTRACT(MONTH FROM sale_date) AS month,
SUM(amount) AS total_sales,
DENSE_RANK() OVER (
ORDER BY SUM(amount) DESC
) AS rnk
FROM sales
GROUP BY
EXTRACT(YEAR FROM sale_date),
EXTRACT(MONTH FROM sale_date)
) ranked
WHERE rnk = 1;
This version returns all months tied for the highest total sales.
๐ Date-based aggregation questions are among the most common in SQL interviews. Practice grouping data by Day, Week, Month, Quarter, Year. You'll encounter these patterns frequently in analytics and reporting roles.
โค๏ธ React with โค๏ธ for more SQL interview challenges!
Post #2921
4.88K
- โค 13