UNPIVOT Clause

    • unpivot_column

    • name_column

    • values_column

    1. CREATE TABLE sales_quarterly (year INT, q1 INT, q2 INT, q3 INT, q4 INT);
    2. INSERT INTO sales_quarterly VALUES
    3. (2020, null, 1000, 2000, 2500),
    4. (2021, 2250, 3200, 4200, 5900),
    5. (2022, 4200, 3100, null, null);
    6. -- column names are used as unpivot columns
    7. SELECT * FROM sales_quarterly
    8. UNPIVOT (
    9. sales FOR quarter IN (q1, q2, q3, q4)
    10. );
    11. +------+---------+-------+
    12. | year | quarter | sales |
    13. +------+---------+-------+
    14. | 2020 | q2 | 1000 |
    15. | 2020 | q3 | 2000 |
    16. | 2020 | q4 | 2500 |
    17. | 2021 | q1 | 2250 |
    18. | 2021 | q2 | 3200 |
    19. | 2022 | q1 | 4200 |
    20. | 2022 | q2 | 3100 |
    21. +------+---------+-------+
    22. -- NULL values are excluded by default, they can be included
    23. -- unpivot columns can be alias
    24. -- unpivot result can be referenced via its alias
    25. SELECT up.* FROM sales_quarterly
    26. UNPIVOT INCLUDE NULLS (
    27. sales FOR quarter IN (q1 AS Q1, q2 AS Q2, q3 AS Q3, q4 AS Q4)
    28. ) AS up;
    29. +------+---------+-------+
    30. | year | quarter | sales |
    31. +------+---------+-------+
    32. | 2020 | Q1 | NULL |
    33. | 2020 | Q2 | 1000 |
    34. | 2020 | Q3 | 2000 |
    35. | 2020 | Q4 | 2500 |
    36. | 2021 | Q1 | 2250 |
    37. | 2021 | Q2 | 3200 |
    38. | 2021 | Q3 | 4200 |
    39. | 2022 | Q1 | 4200 |
    40. | 2022 | Q2 | 3100 |
    41. | 2022 | Q3 | NULL |
    42. | 2022 | Q4 | NULL |
    43. +------+---------+-------+
    44. SELECT * FROM sales_quarterly
    45. UNPIVOT EXCLUDE NULLS (
    46. (first_quarter, second_quarter)
    47. FOR half_of_the_year IN (
    48. (q1, q2) AS H1,
    49. (q3, q4) AS H2
    50. )
    51. );
    52. +------+------------------+---------------+----------------+
    53. | id | half_of_the_year | first_quarter | second_quarter |
    54. +------+------------------+---------------+----------------+
    55. | 2020 | H1 | NULL | 1000 |
    56. | 2020 | H2 | 2000 | 2500 |
    57. | 2021 | H1 | 2250 | 3200 |
    58. | 2021 | H2 | 4200 | 5900 |
    59. +------+------------------+---------------+----------------+