SQL

Pivot Data from Rows to Columns

Transform rows into columns for better data presentation, such as displaying sales per month as separate columns, using conditional aggregation in SQL.

SELECT
  product_name,
  SUM(CASE WHEN month = 'Jan' THEN sales_amount ELSE 0 END) AS Jan_Sales,
  SUM(CASE WHEN month = 'Feb' THEN sales_amount ELSE 0 END) AS Feb_Sales,
  SUM(CASE WHEN month = 'Mar' THEN sales_amount ELSE 0 END) AS Mar_Sales
FROM
  monthly_sales
GROUP BY
  product_name
ORDER BY
  product_name;
How it works: This query pivots data, transforming monthly sales from rows into distinct columns for January, February, and March. It achieves this by using `SUM()` with `CASE` statements. For each `product_name`, it conditionally sums `sales_amount` only when the `month` matches the specified criteria, effectively creating new columns for each month's sales.

Need help integrating this into your project?

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

Hire DigitalCodeLabs