sqlserver 数据库表数据合并
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlserver 数据库表数据合并相关的知识,希望对你有一定的参考价值。
--先把表1和表2的solver合并起来,再分别和表1,表2做连接With T
As
(
Select solver From 表1
union
Select solver From 表2
)
Select T.solver,Isnull(A.amount1,0) As amount1,isnull(B.amount2,0) As amount2 From T
Left Join 表1 A on T.solver=A.solver
Left Join 表2 B on T.solver=B.solver追问
As
(
Select solver From (查询语句1) A
union
Select solver From (查询语句2) B
)
Select T.solver,Isnull(A.amount1,0) As amount1,isnull(B.amount2,0) As amount2 From T
Left Join (查询语句1) A on T.solver=A.solver
Left Join (查询语句2) B on T.solver=B.solver
--你贴个图片也蛮郁闷的,直接把你的语句放进去就可以了,或者先放到临时表,在用刚才的查询,这是MSSQL哦,2005+版本
--以下也可以
Select T.solver,Isnull(A.amount1,0) As amount1,isnull(B.amount2,0) As amount2 From(
Select solver From (查询语句1) A
union
Select solver From (查询语句2) B
) T
Left Join (查询语句1) A on T.solver=A.solver
Left Join (查询语句2) B on T.solver=B.solver 参考技术A 先建好表三,然后执行sql语句:
insert into table3 values(select t1.solver,t1.amount1,t2.amount2 from table1 t1 inner join table2 t2 on t1.solver = t2.solver);
insert into table3 values(select t1.solver,t1.amount1,0 from table1 t1,table t2 where t1.solver <> t2.solver);
insert into table3 values(select t2.solver,0,t2.amount1 from table1 t1,table t2 where t1.solver <> t2.solver);追问
不建表三可以查询出来吗?
追答select t1.solver,t1.amount1,t2.amount2 from table1 t1 inner join table2 t2 on t1.solver = t2.solver
UNION
select t1.solver,t1.amount1,0 from table1 t1,table t2 where t1.solver t2.solver
UNION
select t2.solver,0,t2.amount1 from table1 t1,table t2 where t1.solver t2.solver
试试吧
以上是关于sqlserver 数据库表数据合并的主要内容,如果未能解决你的问题,请参考以下文章
sqlserver 两个表差异合并 除了insert.. select.. 外还有啥最好的办法吗?
sqlserver数据将多个表或视图的数据合并到一个表或视图里的sql语句