我现在有两个表一个是收入表table1,一个是支出表table2.
表1(收入)的数据为:
  datetimes         money
 2008-03-02          10
 2008-03-06          20
 2008-04-12          50
 2008-05-08          90表2(支出)的数据为:
 datetimes          money
 2008-03-05          5
 2008-03-21          10
 2008-04-18          5
 2008-04-25          5
 2008-05-08          30最后想汇总成一个统一表:
 月份       收入合计     支出合计     收支结余    支出占收入比例
2008-3      30          15         15          50%
2008-4      50          10         40          20%
2008-5      90          30         60          67%统一成一个表的每个月份的各项汇总(如上表实现)的SQL语句怎么写!谢谢各位大虾了!

解决方案 »

  1.   

    select m.date 月份,收入合计=m.money,
           支出合计=n.money,
           收支结余=m.money-n.money,
           支出占收入比例=ltrim(n.money*100/m.money)+'%'
    from
    (
      select date=convert(char(7),datetimes,120),sum(money) money
      from tb1
      group by convert(char(7),datetimes,120)
    ) m
      join
    (
      select date=convert(char(7),datetimes,120),sum(money) money
      from tb2
      group by convert(char(7),datetimes,120)
    ) n
    on m.date=n.date
      

  2.   

    --> 测试数据: #1
    if object_id('tempdb.dbo.#1') is not null drop table #1
    create table #1 (datetimes datetime,money int)
    insert into #1
    select '2008-03-02',10 union all
    select '2008-03-06',20 union all
    select '2008-04-12',50 union all
    select '2008-05-08',90
    --> 测试数据: #2
    if object_id('tempdb.dbo.#2') is not null drop table #2
    create table #2 (datetimes datetime,money int)
    insert into #2
    select '2008-03-05',5 union all
    select '2008-03-21',10 union all
    select '2008-04-18',5 union all
    select '2008-04-25',5 union all
    select '2008-05-08',30
    select
    月份=isnull(a.ym,b.ym),
    收入合计=isnull(a.[in],0),
    支出合计=isnull(b.[out],0),
    收支结余=isnull(a.[in],0)-isnull(b.[out],0),
    支出占收入比例=1.0*isnull(b.[out],0)/a.[in]
    from
    (select ym=convert(char(7),datetimes,120),[in]=sum(money) from #1 group by convert(char(7),datetimes,120)) a
    full join
    (select ym=convert(char(7),datetimes,120),[out]=sum(money) from #2 group by convert(char(7),datetimes,120)) b
    on a.ym=b.ym/*
    月份    收入合计    支出合计    收支结余    支出占收入比例
    ------- ----------- ----------- ----------- ---------------------------------------
    2008-03 30          15          15          0.500000000000
    2008-04 50          10          40          0.200000000000
    2008-05 90          30          60          0.333333333333
    */
      

  3.   

    怎么都提示:
    服务器: 消息 207,级别 16,状态 3,行 1
    列名 'datetime' 无效。
    服务器: 消息 207,级别 16,状态 1,行 1
    列名 'datetime' 无效。
    服务器: 消息 207,级别 16,状态 1,行 1
    列名 'datetime' 无效。
    服务器: 消息 207,级别 16,状态 1,行 1
    列名 'datetime' 无效。
    服务器: 消息 207,级别 16,状态 1,行 1我把上面二位的写的“datetimes”已经改成datetime怎么还有错啊?