Careeroza
Pivoting Data
Rows to Columns
A pivot turns values from rows into columns, for example one column per month. The portable way is conditional aggregation with CASE.
Example
Revenue per employee per month, as columns:
SELECT e.FirstName,
SUM(CASE WHEN strftime('%m', o.OrderDate) = '01' THEN o.Amount ELSE 0 END) AS Jan,
SUM(CASE WHEN strftime('%m', o.OrderDate) = '02' THEN o.Amount ELSE 0 END) AS Feb,
SUM(CASE WHEN strftime('%m', o.OrderDate) = '03' THEN o.Amount ELSE 0 END) AS Mar,
SUM(CASE WHEN strftime('%m', o.OrderDate) = '04' THEN o.Amount ELSE 0 END) AS Apr
FROM Orders o
JOIN Employees e ON e.EmployeeID = o.EmployeeID
GROUP BY e.FirstName;Result: 2 rows
| FirstName | Jan | Feb | Mar | Apr |
|---|---|---|---|---|
| David | 89.9 | 56.25 | 27 | 0 |
| Sara | 245.5 | 412 | 320.75 | 198.4 |
PIVOT Operator
-- SQL Server
SELECT *
FROM (SELECT EmployeeID, DATENAME(month, OrderDate) AS Mon, Amount FROM Orders) AS src
PIVOT (SUM(Amount) FOR Mon IN ([January], [February], [March])) AS p;PostgreSQL offers crosstab() in the tablefunc extension. In most cases, the CASE version above is simpler and works everywhere.
Exercise
Exercise: Using a window function, list each product with its price and the price of the next cheaper product in the same category.
Show answer
SELECT ProductName, Category, Price,
LEAD(Price) OVER (PARTITION BY Category ORDER BY Price DESC) AS NextCheaper
FROM Products;