SQL怎么合并表?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL怎么合并表?相关的知识,希望对你有一定的参考价值。

表一表二表三合并起来 成为表四的效果,怎么弄?如图
用SQL语句写

select * into 新表名 from (select * from T1 union all select * from T2)

这个语句可以实现将合并的数据追加到一个新表中。

不合并重复数据 select * from T1 union all select * from T2

合并重复数据 select * from T1 union select * from T2

两个表,表1 表2

如果要将 表1的数据并入表2用以下语句即可

insert into 表2(字段1,字段2) select 字段1,字段2 from b1

注意,必须把字段名全部写清楚,而且不允许把自动编号进去写进去,要合并自动编号字段必须重写一个算法一条一条记录地加进去

1 insert into b1 select * from b2

2 select * into newtable from (select * from b1 union all select * from b2)
参考技术A 2个 left join 就搞定。

sql sqlserver合并表演示

MERGE into dbo.water_quality_data_his AS target
USING dbo.water_quality_data_his_temp AS source
ON (target.id = source.id)
    WHEN MATCHED
        THEN UPDATE SET
        target.[id] = source.[id],
        target.[point_id] = source.[point_id],
        target.[item_id] = source.[item_id],
        target.[item_name] = source.[item_name],
        target.[item_unit] = source.[item_unit],
        target.[value] = source.[value],
        target.[moni_time] = source.[moni_time],
        target.[flag] = source.[flag],
        target.[lower_limit] = source.[lower_limit],
        target.[upper_limit] = source.[upper_limit],
        target.[dec] = source.[dec],
        target.[update_time] = source.[update_time]
    when not matched by target
        then insert
        values(
            source.[id],
            source.[point_id],
            source.[item_id],
            source.[item_name],
            source.[item_unit],
            source.[value],
            source.[moni_time],
            source.[flag],
            source.[lower_limit],
            source.[upper_limit],
            source.[dec],
            source.[update_time]
        );
    --when not matched by source
    --    then delete
    --OUTPUT $action, Inserted.*, Deleted.*;

以上是关于SQL怎么合并表?的主要内容,如果未能解决你的问题,请参考以下文章

sql合并两张表(表字段不一致)到一张新表中

SQL怎么列合并

SQL 两张表合并 (两张表的列都相同)

请问:SQL 同字段名,不同字段值怎么合并

如何用sql语句将三张表合并为一张表

求助:SQLSERVER多条查询语句合并