SQL
Create a Simple Pivot Table (Rows to Columns)
Transform rows into columns using SQL for clearer data representation and reporting, enabling easy comparison of categorical data across different attributes.
-- Example: Monthly sales for different product categories
SELECT
DATE_TRUNC('month', order_date) AS sales_month,
SUM(CASE WHEN product_category = 'Electronics' THEN total_amount ELSE 0 END) AS electronics_sales,
SUM(CASE WHEN product_category = 'Books' THEN total_amount ELSE 0 END) AS books_sales,
SUM(CASE WHEN product_category = 'Clothing' THEN total_amount ELSE 0 END) AS clothing_sales
FROM
orders
GROUP BY
sales_month
ORDER BY
sales_month;
How it works: This SQL query demonstrates how to create a simple pivot table, transforming distinct row values from one column into separate columns. It uses SUM with CASE WHEN expressions to conditionally aggregate sales amounts for different product_category values (Electronics, Books, Clothing) and then groups the results by sales_month. This provides a cross-tabulated view, ideal for comparing categories side-by-side over time.