sql—将一个表复制到另一个具有不同列的表

rdrgkggo  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(579)

我有一个表a列是(id,name,a,b,c,p\u id)
我想把tablea转换成tableb,tableb列是(id,name,alphabets,alphabets\u value,p\u id)

表A中的记录

id | name | A | B | C | p_id
1  | xyz  | a | b |   | 1
2  | opq  | a`| b`| c`| 1

应在表B中

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

我想要当前使用microsoft sql的tableb输出

j91ykkif

j91ykkif1#

这是一个不独立的概念,可能最容易用一个联合体来解释:

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

然后,您可以从何处删除空值,以及行\号以给自己一个假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

一旦得到了所需的结果集,插入、更新或合并到表b中就非常简单了

相关问题