Unpivot Columns Into Rows With Unnest
Multi-argument unnest in the FROM clause expands parallel arrays of labels and values, turning one wide row into one row per month without UNION ALL repetition.
Code
-- 宽表转长表(unpivot):FROM 里的多参数 unnest 把标签数组与
-- 数值数组并行展开,一行宽表逐列变成多行
WITH monthly AS (
SELECT * FROM (VALUES
('p1', 120, 80, 0),
('p2', 0, 210, 95)
) AS t(product_id, jan_cents, feb_cents, mar_cents)
)
SELECT product_id, u.month, u.cents
FROM monthly,
unnest(ARRAY['jan', 'feb', 'mar'],
ARRAY[jan_cents, feb_cents, mar_cents]) AS u(month, cents)
ORDER BY product_id, u.month;
-- 等价的 UNION ALL 写法:每个分支手写一列,月份一多就冗长且容易漏
WITH monthly AS (
SELECT * FROM (VALUES
('p1', 120, 80, 0),
('p2', 0, 210, 95)
) AS t(product_id, jan_cents, feb_cents, mar_cents)
)
SELECT product_id, 'jan' AS month, jan_cents AS cents FROM monthly
UNION ALL
SELECT product_id, 'feb', feb_cents FROM monthly
UNION ALL
SELECT product_id, 'mar', mar_cents FROM monthly;Inside the snippet
Several statements share this file — SELECT, with monthly among the objects involved.
Concretely, the SQL combines: a CTE (WITH … AS) that names an intermediate result before the main query; an ORDER BY that fixes the output order; a UNION combining result sets from separate queries.
Putting it to use
Point it at the monthly table.
Core lines
WITH monthly AS (
SELECT * FROM (VALUES
('p1', 120, 80, 0),
('p2', 0, 210, 95)
) AS t(product_id, jan_cents, feb_cents, mar_cents)
)
SELECT product_id, 'jan' AS month, jan_cents AS cents FROM monthly
UNION ALL
SELECT product_id, 'feb', feb_cents FROM monthly
UNION ALL
SELECT product_id, 'mar', mar_cents FROM monthly;
WITH monthly AS (
SELECT * FROM (VALUES
('p1', 120, 80, 0),
('p2', 0, 210, 95)
) AS t(product_id, jan_cents, feb_cents, mar_cents)
)
SELECT product_id, u.month, u.cents
FROM monthly,
unnest(ARRAY['jan', 'feb', 'mar'],
ARRAY[jan_cents, feb_cents, mar_cents]) AS u(month, cents)
ORDER BY product_id, u.month;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Name the tables involved in this file.
- `monthly`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.