SQL

Performing Conditional Aggregation for Dynamic Pivoting

Transform rows into columns and summarize data based on specific conditions using SQL's CASE WHEN expressions within aggregate functions for insightful reports.

SELECT
    product_id,
    SUM(CASE WHEN sale_month = 'Jan' THEN sale_amount ELSE 0 END) AS Sales_Jan,
    SUM(CASE WHEN sale_month = 'Feb' THEN sale_amount ELSE 0 END) AS Sales_Feb,
    SUM(CASE WHEN sale_month = 'Mar' THEN sale_amount ELSE 0 END) AS Sales_Mar,
    SUM(sale_amount) AS Total_Sales -- Optional: Total sales across all selected months
FROM (
    -- Subquery to extract month or other relevant grouping column
    SELECT
        product_id,
        DATE_FORMAT(sale_date, '%b') AS sale_month, -- For MySQL. Use TO_CHAR(sale_date, 'Mon') for PostgreSQL, FORMAT(sale_date, 'MMM') for SQL Server
        amount AS sale_amount
    FROM sales
    WHERE sale_date >= '2023-01-01' AND sale_date < '2023-04-01'
) AS MonthlySales
GROUP BY product_id
ORDER BY product_id;

-- Example 'sales' table structure:
-- CREATE TABLE sales (
--     sale_id INT PRIMARY KEY AUTO_INCREMENT,
--     product_id INT,
--     sale_date DATE,
--     amount DECIMAL(10, 2)
-- );
-- INSERT INTO sales (product_id, sale_date, amount) VALUES
-- (101, '2023-01-05', 100.00),
-- (102, '2023-01-15', 250.50),
-- (101, '2023-02-10', 120.00),
-- (103, '2023-02-20', 300.00),
-- (102, '2023-03-01', 180.00),
-- (101, '2023-03-25', 90.00);
How it works: This query uses `CASE WHEN` expressions inside aggregate functions (`SUM`) to perform conditional aggregation, effectively "pivoting" data. It transforms distinct values from a row (e.g., months) into separate columns, allowing for a summarized, wider result set often used in reporting dashboards and business intelligence applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs