Write a SQL query to perform a pivot transformation without using the PIVOT function.

Instruction: Without PIVOT, use PostgreSQL conditional aggregation for sales(product, year_no, amount). Show fixed columns for 2024 and 2025, sum legitimate multiple sales per product/year, and preserve NULL for a year with no contributing amount.

Context: This question challenges the candidate to demonstrate advanced SQL skills by manually replicating the functionality of built-in pivot operations.

Updated

Official answer

Use conditional aggregation over a defined product/year grain. This PostgreSQL fixture preserves the distinction between an absent year and known zero sales:

WITH sales(product, year_no, amount) AS (
  VALUES ('A',2024,10), ('A',2024,5), ('A',2025,0), ('B',2025,8)
)
SELECT product,
       SUM(CASE WHEN year_no = 2024 THEN amount END) AS sales_2024,
       SUM(CASE WHEN year_no = 2025 THEN amount END) AS sales_2025
FROM sales
GROUP BY product
ORDER BY product;

The output is A=(15,0) and B=(NULL,8). Multiple legitimate sales rows are deliberately summed. NULL means no non-NULL amount contributed to that year; it does not establish zero sales. Use COALESCE only when the data and reporting contract justify that interpretation.

The chosen years become fixed output columns. Dynamic years require controlled generation or a reporting-layer transformation, not value parameters pretending to be column names. Decide how unknown amounts, unexpected years and products absent from all source rows should appear.

Related Questions