首页 > 解决方案 > 如何将许多(和不同的)单元格从一行合并到具有较少单元格的多行?

问题描述

我迷失了如何完成这样的转换,从(1行有一对相同类型的列重复3次):

NormalCol1 | NormalCol2 | col1_0 | col2_0 | col1_1 | col2_2 | col1_2 | col2_2
"AD"       | 2018-03-02 | "error"| "mess" | "warn" | "mess" | "info" | "mess"

to(3 行,这 6 列放在一起 2):

NormalCol1 | NormalCol2 | col1   | col2 
"AD"       | 2018-03-02 | "error"| "mess"
"AD"       | 2018-03-02 | "warn" | "mess"
"AD"       | 2018-03-02 | "info" | "mess"

你有没有偶然发现这样的转变?如果是,您是如何完成转型的?

Ps:列是固定的。

标签: sqlsql-server

解决方案


使用UNION ALL查询或CROSS APPLYunion all也)或TABLE VALUE CONSTRUCTOR

SELECT NormalCol1, NormalCol2, col1 = col1_0, col2 = col2_0 FROM YourTable
UNION ALL
SELECT NormalCol1, NormalCol2, col1 = col1_1, col2 = col2_1 FROM YourTable
UNION ALL
SELECT NormalCol1, NormalCol2, col1 = col1_2, col2 = col2_2 FROM YourTable


SELECT NormalCol1, NormalCol2, col1, col2
FROM   YourTable
       CROSS APPLY
       (
           SELECT col1 = col1_0, col2 = col2_0
           UNION ALL
           SELECT col1 = col1_1, col2 = col2_1
           UNION ALL
           SELECT col1 = col1_2, col2 = col2_2
       ) a

SELECT NormalCol1, NormalCol2, col1, col2
FROM   YourTable
       CROSS APPLY
       (
           VALUES (col1_0, col2_0), 
                  (col1_1, col2_1),
                  (col1_2, col2_2)
       ) c (col1, col2)

推荐阅读