用全連接吧,full join Select a.*,b.*  From a full join b on ........

解决方案 »

  1.   

    SELECT 编码,年度,月,当月,累计,上月,支出,0 收入 FROM 表1
    UNION ALL
    SELECT 编码,年度,月,当月,累计,上月,0 支出, 收入 FROM 表2
      

  2.   

    select a.编码,a.年度,a.月,a.当月,a.累计,a.上月,支出,收入 from 表1 a,表2 b where a.编码=b.编码
      

  3.   

    select a.*, b.支出
    from 表1 a
    INNER JOIN 表2 b
    ON a.编码 = b.编码 AND a.年度 = b.年度 AND a.月 = b.月
      

  4.   

    ---测试数据---
    if object_id('[ta]') is not null drop table [ta]
    go
    create table [ta]([编码] int,[年度] int,[月] varchar(2),[当月] int,[累计] int,[上月] int,[收入] int)
    insert [ta]
    select 196207,2008,'01',514,1028,0,0 union all
    select 196308,2008,'01',424,848,0,0 union all
    select 196607,2008,'01',435,870,0,0 union all
    select 196608,2008,'01',396,792,0,0
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([编码] int,[年度] int,[月] varchar(2),[当月] int,[累计] int,[上月] int,[支出] int)
    insert [tb]
    select 196207,2008,'01',514,1028,0,0 union all
    select 196308,2008,'01',424,848,0,0 union all
    select 196607,2008,'01',435,870,0,0 union all
    select 196608,2008,'01',396,792,0,0
     
    ---查询---
    select 编码,年度,月,当月,累计,上月,0 as 支出, 收入 from ta
    union all
    select 编码,年度,月,当月,累计,上月,支出,0 as 收入 from tb---结果---
    编码          年度          月    当月          累计          上月          支出          收入          
    ----------- ----------- ---- ----------- ----------- ----------- ----------- ----------- 
    196207      2008        01   514         1028        0           0           0
    196308      2008        01   424         848         0           0           0
    196607      2008        01   435         870         0           0           0
    196608      2008        01   396         792         0           0           0
    196207      2008        01   514         1028        0           0           0
    196308      2008        01   424         848         0           0           0
    196607      2008        01   435         870         0           0           0
    196608      2008        01   396         792         0           0           0(所影响的行数为 8 行)