[英]copy one table to another table with diffrent columns
I have a TableA columns are (id,name,A,B,C,p_id)我有一个 TableA 列是(id,name,A,B,C,p_id)
i want convert TableA to TableB, TableB columns are (id,name,alphabets,alphabets_value,p_id)我想将 TableA 转换为 TableB,TableB 的列是 (id,name,alphabets,alphabets_value,p_id)
id | name | A | B | C | p_id
1 | xyz | a | b | | 1
2 | opq | a`| b`| c`| 1
u_id | id | name | alphabets | alphabets_value | p_id
1 | 1 | xyz | A | a | 1
2 | 1 | xyz | B | b | 1
3 | 2 | opq | A | a` | 1
4 | 2 | opq | B | b` | 1
5 | 2 | opq | C | c` | 1
i want TableB output currently using Microsoft SQL我想要 TableB output 当前使用 Microsoft SQL
This is an unpivot, probably most easily explained by a UNION ALL:这是一个 unpivot,可能最容易用 UNION ALL 解释:
SELECT id, name, 'A' as alphabets, a as alphabets_value, p_id
UNION ALL
SELECT id, name, 'B' as alphabets, b as alphabets_value, p_id
UNION ALL
SELECT id, name, 'C' as alphabets, c as alphabets_value, p_id
You can then WHERE to remove the nulls from this, and ROW_NUMBER to give yourself a fake U_id:然后,您可以在 WHERE 中删除其中的空值,并使用 ROW_NUMBER 给自己一个假的 U_id:
SELECT ROW_NUMBER() OVER(ORDER BY id, alphabets) as u_id, x.*
FROM
(
SELECT id, name, 'A' as alphabets, a as alphabets_value, p_id
UNION ALL
SELECT id, name, 'B' as alphabets, b as alphabets_value, p_id
UNION ALL
SELECT id, name, 'C' as alphabets, c as alphabets_value, p_id
)
WHERE
x.alphabets_value IS NOT NULL
Once you get to having a result set you want, INSERT INTO, UPDATE FROM or MERGE to get it into table B is quite trivial一旦你得到一个你想要的结果集,INSERT INTO、UPDATE FROM 或 MERGE 将它放入表 B 中是非常简单的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.