sqlserver 把两个sql查询语句查询出来的两张表合并成一张表

时间:2022-09-06 14:52:16

第一个sql语句

select companyname gsmc,zb zhibiao
from t_gsndzb left join t_companycode
on t_gsndzb.gsbh=t_companycode.companyid

查询结果:

sqlserver 把两个sql查询语句查询出来的两张表合并成一张表

第二个sql语句

SELECT min(companyname) gsmc,cast(round(sum(t_xstj.hsje)/10000,2)   as   numeric(20,2))  ndje FROM t_xstj left join t_companycode 
on t_companycode.companyid = t_xstj.gsbh
where datediff(year,sj,getdate())=0 group by gsbh

查询结果:

sqlserver 把两个sql查询语句查询出来的两张表合并成一张表

 

合并成一张表的语句:

select isnull(a.gsmc,b.gsmc) gsmc,isnull(a.zhibiao,0) zhibiao,isnull(b.ndje,0) ndje
from (
      --第二个表查询结果--
      select companyname gsmc,zb zhibiao 
      from t_gsndzb left join t_companycode 
      on t_gsndzb.gsbh=t_companycode.companyid
      ) 
A FULL JOIN (
          --第二个表查询结果--
             SELECT min(companyname) gsmc,
             cast(round(sum(t_xstj.hsje)/10000,2)   as   numeric(20,2))  ndje 
             FROM t_xstj left join t_companycode 
             on t_companycode.companyid = t_xstj.gsbh
             where datediff(year,sj,getdate())=0 group by gsbh
) b 
on a.gsmc=b.gsmc

结果:

sqlserver 把两个sql查询语句查询出来的两张表合并成一张表