使用格式将数据移动或插入其他SQL表

时间:2014-08-19 10:12:06

标签: sql sql-server-2008

我试图将我的数据从一个表移动到另一个表是sql serve r。

问题是新表有新结构而不是旧表。

这是我的旧表:

Column 0    Column 1    Column 2    Column 3    Column 4    Column 5
12312323      07:31      15:30                               6390
12312342      07:31      15:21                               6390
12334323      07:21      09:20       12:30      15:04        93444
12323323      07:28      10:05       11:28      15:09        93444
23512323      07:26      08:21       14:04      14:34        93444
12452323      07:16      10:44       11:53      15:08        93444

"第0列和第34列;是用户ID,其他列是用户小时/时钟与系统的交互。

现在我想在另一个表中获得此输出:

Column 0    Column 1    Column 2    Column 3
12312323      07:31      15:30      6390                                                            
12312342      07:31      15:21      6390                                                            
12334323      07:21      09:20      93444
12334323      12:30      15:04      93444                                               
12323323      07:28      10:05      93444
12323323      11:28      15:09      93444
23512323      07:26      08:21      93444                                                                   
23512323      14:04      14:34      93444
12452323      07:16      10:44      93444
12452323      11:53      15:08      93444

正如你在第二个表中看到的那样,即时删除表格中的每一行,其中包含" Column3,Column4"并将它们在下一行添加到新表中

2 个答案:

答案 0 :(得分:2)

我认为您可以使用UNION ALL来获得所需的结果:

INSERT INTO new_table
SELECT   [Column 0], [Column 1], [Column 2], [Column 5]
FROM     old_table
UNION ALL
SELECT   [Column 0], [Column 3], [Column 4], [Column 5]
FROM     old_table
WHERE    [Column 3] IS NOT NULL AND [Column 4] IS NOT NULL

答案 1 :(得分:2)

最简单的方法是使用union all

select col0, col1, col2, col5
from oldtable
union all
select col0, col1, col3, col4
from oldtable
where col3 is not null;

如果您想将其放入新表格,请使用insertselect into。例如:

select col0, col1, col3, col4
into newtable
from (select col0, col1, col2 as col3, col5 as col4
      from oldtable
      union all
      select col0, col1, col3, col4
      from oldtable
      where col3 is not null
     ) t