【问题标题】:Stacking multiple tables in SQL server [duplicate]在SQL Server中堆叠多个表[重复]
【发布时间】:2015-07-17 21:47:22
【问题描述】:

我实际上是在尝试在多个表上执行 UNION 并让结果成为一个新表。我知道我可以这样做来选择和堆叠所有行:

SELECT * FROM table1
UNION ALL
SELECT * FROM table2
UNION ALL
SELECT * FROM table3
....

但是我如何把它变成它自己的表呢?

谢谢!

【问题讨论】:

  • into放在第一个selectselect * into newtable from table1 . . .

标签: sql sql-server sql-server-2008


【解决方案1】:

一种方式:

SELECT * INTO [new_tablename] FROM table1

UNION ALL
SELECT * FROM table2
UNION ALL
SELECT * FROM table3

【讨论】:

    【解决方案2】:

    ANSI 版本:

    create table supremeTable ( oneOfYourManyGreatColumns int, ... );

    insert into supremeTable
        select * from table1
        union all
        select * from table2...;
    

    甚至

    merge into supremeTable as _d
    using (
        select * from table 1
        union all...
    ) as _s
    on 0 = 1
    when not matched then
        insert (
            thisAllowsYouTo,
            changeTheColumnMappings
        )
        values (
            _s.fromTheSourceTables,
            _s.toTheDestination
        ); -- don't forget that ANSI semicolon!
    

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 2017-05-18
      • 1970-01-01
      • 2011-03-29
      • 2017-10-03
      • 2013-03-11
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      相关资源
      最近更新 更多