将列转换为行
在上一个练习中,您把行中的产品名称转换为列,并按年份汇总了各产品的销售数量。
假设您已将上一个练习的结果保存到名为 pivot_sales 的新表中,现在希望把 notebooks、pencils 和 crayons 这些列转换为行值。
期望的结果如下:
| year_of_sale | units | product_name |
|--------------|-------|--------------|
| 2018 | 150 | notebooks |
| 2018 | 150 | pencils |
| 2018 | 80 | crayons |
| 2019 | 230 | notebooks |
| 2019 | 130 | pencils |
| 2019 | 170 | crayons |
本练习是课程的一部分
在 SQL Server 数据库中清洗数据
练习说明
- 使用合适的运算符将列转换为行。
- 写出用于存放被转换列名的结果列名称。
- 写出您想要转换为行的列名。
- 将
UNPIVOT运算符起别名为unpivot_sales。
交互式实操练习
通过完成这段示例代码来试试这个练习。
SELECT * FROM pivot_sales
-- Use the operator to convert columns into rows
___
-- The resulting column that will contain the turned columns into rows
(units FOR ___ IN (___, ___, ___))
-- Give the alias name
AS ___