facebook pixel
Day 2/7 - SQL Challenge šŸŽÆ TODAY'S QUESTION: Calculate total sales for each month in 2024. TABLE: Orders (id, customer_id, amount, order_date) THE SOLUTION: SELECT DATE_FORMAT(order_date, '%Y-%m') as month, SUM(amount) as total_sales FROM Orders WHERE YEAR(order_date) = 2024 GROUP BY month ORDER BY month; BREAKDOWN: DATE_FORMAT(order_date, '%Y-%m') - Extracts year-month (2024-01, 2024-02, etc.) WHERE YEAR(order_date) = 2024 - Filters only 2024 data GROUP BY month - Groups all sales by month SUM(amount) - Adds up all sales per month ORDER BY month - Shows chronologically COMMON MISTAKES: āŒ Not formatting date (GROUP BY raw dates) āŒ Forgetting WHERE clause (includes all years) āŒ Wrong date function syntax ALTERNATIVE (PostgreSQL): SELECT TO_CHAR(order_date, 'YYYY-MM') as month, SUM(amount) as total_sales FROM Orders WHERE EXTRACT(YEAR FROM order_date) = 2024 GROUP BY month ORDER BY month; WHY THIS IS ASKED: Tests your understanding of: Date functions (every SQL dialect has differ...

Ā 8.4k

Ā 166

Ā 15

Ā 8.4k

    Suggested Credits
    Tags, Events, and Projects