Pandas → T-SQL › pivot_table

Pandas pivot_table to GROUP BY / PIVOT

Most pivot_tables at work are a GROUP BY that someone formatted wide. Start narrow, then PIVOT.

SELECT customer_id,
       SUM(CASE WHEN status = 'Shipped' THEN total_amount ELSE 0 END) AS Shipped,
       SUM(CASE WHEN status = 'Cancelled' THEN total_amount ELSE 0 END) AS Cancelled
FROM Orders
GROUP BY customer_id;

fill_value=0 is ELSE 0. ISNULL after a PIVOT also works.

Canonical translation

SELECT customer_id,
       SUM(CASE WHEN status = 'Shipped' THEN total_amount ELSE 0 END) AS Shipped,
       SUM(CASE WHEN status = 'Cancelled' THEN total_amount ELSE 0 END) AS Cancelled
FROM Orders
GROUP BY customer_id;

Then write it on a ticket

Monday is free. A colleague asks, you type, we mark it.

Clock in free