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.

SqlData Fetching

Code

sqlsnippet
26 lines
-- 宽表转长表(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

FAQ

Name the tables involved in this file.
`monthly`.