sql - 如何将许多(和不同的)单元格从一行合并到具有较少单元格的多行?
问题描述
我迷失了如何完成这样的转换,从(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:列是固定的。
解决方案
使用UNION ALL
查询或CROSS APPLY
(union 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)
推荐阅读
- javascript - 快递网站赠送503
- java - 并行使用蒙特卡罗方法计算 Pi
- python - 虽然循环不能识别多个条件
- reactjs - 符号 &tagname 的含义:用于材质 UI 中的 css 样式。例如:&div: { display: 'flex' '}
- git - 有没有办法使用 microdnf 将 git 安装到 RedHat ubi 8 最小映像中并解决安装 shadow-utils 的错误?
- php - 如何在 Perl 文件中检索 PHP 会话?
- symfony - LANG 变量在测试环境中未被覆盖
- powershell - 使用模式 [Powershell] 重命名目录上的所有文件
- gdb - 使用带有别名的 gdb 运行 python 脚本
- javascript - 在threejs中使用toneMapping时如何避免背景图像由白色变为灰色?