(Database) Row to column (unpivot), column to row (pivot) in SQL

1. Row to Columnunpivot()

This is a SQLServer function, not available in MySQL

1.1 Objectives

Convert the following table 1 to the format shown in table 2

ID Phone1 Phone2
1 11 12
2 21 23
ID Phone_num Phone_type
1 11 Phone1
1 12 Phone2
2 21 Phone1
2 22 Phone2

1.2 Code and explanation

Depending on the target requirements, we need to:

  1. Create two new columns Phone_num, Phone_type
  2. Delete the Phone1, Phone2 columns of the old table and use their column names as elements of the new column Phone_type
  3. Populate these two new columns based on ID
select * from Customers
unpivot (
    -- 创建新列: Phone_num
    Phone_num
    -- 创建新列: Phone_type
    -- 删除旧列: Phone1, Phone2,并将它们的列名作为 Phone_type 的值
    -- 遍历这些列名,结合ID,查找旧表中的电话数据填入 Phone_num
    for Phone_type in (Phone1, Phone2)
) as up;

2. Column to rowpivot()

The goal is the opposite of the previous part:

ID Phone_num Phone_type
1 11 Phone1
1 12 Phone2
2 21 Phone1
2 22 Phone2
ID Phone1 Phone2
1 11 12
2 21 23

Depending on the goal, we need to:

  1. Delete the Phone_num, Phone_type columns of the old table and use their elements as the column names of the new table
  2. Create these two new columns Phone1, Phone2
  3. Populate a new column based on ID and Phone_type
select * from Customers
pivot (
	-- 删除旧列: Phone_nume
	-- 这里必须是一个聚合函数 Aggregation,例如 sum() avg()
	-- 因此这要求电话号码的格式必须为数字,不能是字符串
    sum(Phone_num)
    -- 创建新列: Phone1, Phone2
    -- 删除旧列: Phone_type
    -- 遍历这些列名,结合ID,查找旧表中的电话数据填入新表
    for Phone_type in (Phone1, Phone2)
) as up;

Guess you like

Origin blog.csdn.net/weixin_43728138/article/details/123635563