SQL

Perform Conditional Aggregation for Data Pivoting

Transform row-based data into a more readable, column-based format by aggregating values conditionally, creating a simple pivot table in SQL.

SELECT
    SUM(CASE WHEN category = 'Electronics' THEN sales_amount ELSE 0 END) AS total_electronics_sales,
    SUM(CASE WHEN category = 'Books' THEN sales_amount ELSE 0 END) AS total_books_sales,
    SUM(CASE WHEN category = 'Home Goods' THEN sales_amount ELSE 0 END) AS total_home_goods_sales
FROM orders;
How it works: This snippet demonstrates conditional aggregation, a technique to pivot data. It uses `CASE` statements within `SUM` to sum 'sales_amount' only for specific categories, effectively creating new columns for each category's total sales. This transforms category-specific rows into a summary row with category-specific columns.

Need help integrating this into your project?

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

Hire DigitalCodeLabs