选择Insert like like unpivot和pivot

问题描述 投票:0回答:1

表格1:

kode  | 101  | 102 | 103   | 104
=================================
1234  | 100  | 200 | 300   | 400
4555  | 1200 | 130 | 14500 | 1550
5012  | 100  | 150 | 350   | 440

表2:

kode  | field1 | field2
=======================
1234  | 101    | 100
1234  | 102    | 200
1234  | 103    | 300
1234  | 104    | 400
4555  | 101    | 1200
4555  | 102    | 130
4555  | 103    | 14500
4555  | 104    | 1550
5012  | 101    | 100
5012  | 102    | 150
5012  | 103    | 350
5012  | 104    | 440

我有table-1中的数据,如何使用sql查询插入来自table-1 totable-2的数据,如使用set @cols来旋转哪个动态

sql-server
1个回答
1
投票

您可以使用UNPIVOT创建所需的数据集。假设你的表看起来像这样:

create table table1 (
    kode int,
    [101] int,
    [102] int,
    [103] int,
    [104] int
);

insert into table1 values
(1234  , 100  , 200 , 300   , 400),
(4555  , 1200 , 130 , 14500 , 1550),
(5012  , 100  , 150 , 350   , 440);

您的查询将如下所示

SELECT kode, field1, field2
FROM table1
UNPIVOT 
(
  field2 FOR field1 IN ([101], [102], [103], [104])
) AS up;

这将给你想要的结果。

让我们有一个像这样的新表

create table table2 (
    kode int,
    field1 int,
    field2 int
);

将UNPIVOT的数据填充到table2中

insert into table2
SELECT kode, field1, field2
FROM table1
UNPIVOT 
(
  field2 FOR field1 IN ([101], [102], [103], [104])
) AS up;

select * from table2;

示例:https://rextester.com/YPWG93602

© www.soinside.com 2019 - 2024. All rights reserved.