表H
合同id 承接单位 合同金额
1       1        1000
2       1        2000
3       1        3000
4       2        4000
5       2        5000
表M
拨款ID 合同ID 拨款金额 拨款次数
1 1 200 1
2 1 300 2
3 1 500 3
4 2 1000 1
5 2 1000 2
6 3 500 1
7 3 1500 2
8 4 2000 1
9 4 2000 2
10 5 5000 1统计结果
承建单位 合同数量 总金额 总拨款金额 剩余金额
1  3   6000         5000         1000
2  2   9000         9000         0
注:剩余金额=合同金额-拨款金额求高人帮忙写个sql文

解决方案 »

  1.   


    select b.承建单位,count(distinct a.合同ID) as [合同数量],(select sum(合同金额) from 表H where 承接单位 = b.承建单位) as [总金额],sum(拨款金额) as [总拨款金额],(select sum(合同金额) from 表H where 承接单位 = b.承建单位) - sum(拨款金额) as [剩余金额]
    from 表H a join 表M on a.合同id = b.合同id
    group by b.承建单位
      

  2.   

    select
     b.承建单位,
     count(distinct a.合同ID) as [合同数量],
    (select sum(合同金额) from 表H where 承接单位 = b.承建单位) as [总金额],
            sum(拨款金额) as [总拨款金额],
    (select sum(合同金额) from 表H where 承接单位 = b.承建单位) - sum(拨款金额) as [剩余金额]
    from
     表H a join 表M on a.合同id = b.合同id
    group by
     b.承建单位
      

  3.   


    if object_id('表H') is not null 
    drop table 表H
    go
    Create table 表H
    (合同id int, 承接单位 int, 合同金额 int)
    go
    insert into 表H 
    select 1, 1, 1000 union all
    select 2,  1, 2000 union all
    select 3,  1, 3000 union all
    select 4,  2, 4000 union all
    select 5,  2, 5000
    goif object_id('表M') is not null 
    drop table 表M
    go
    Create table 表M
    (拨款ID int, 合同ID int, 拨款金额 int, 拨款次数 int)
    go
    insert into 表M
    select 1, 1, 200, 1 union all
    select 2, 1, 300 ,2 union all
    select 3, 1, 500, 3 union all
    select 4, 2, 1000, 1 union all
    select 5, 2, 1000, 2 union all
    select 6, 3, 500 ,1 union all
    select 7, 3, 1500 ,2 union all
    select 8, 4, 2000 ,1 union all
    select 9, 4, 2000, 2 union all
    select 10, 5, 5000, 1
    go
    select a.承接单位,sum(a.承接单位)as 合同数量
    ,sum(a.合同金额) as 总金额
    ,(select sum(拨款金额) from 表M where 合同ID in(select 合同id from 表H where 表H.承接单位 = a.承接单位) ) as 总拨款金额
    ,(sum(a.合同金额)-(select sum(拨款金额) from 表M where 合同ID in(select 合同id from 表H where 表H.承接单位 = a.承接单位) )) as 剩余金额
    from 表H a group by 承接单位
      

  4.   

    select b.承建单位,count(distinct a.合同ID) as [合同数量],
    (select sum(合同金额) from 表H where 承接单位 = b.承建单位) as [总金额],sum(拨款金额) as [总拨款金额],
    (select sum(合同金额) from 表H where 承接单位 = b.承建单位) - sum(拨款金额) as [剩余金额]
    from 表H a join 表M on a.合同id = b.合同id
    group by b.承建单位
      

  5.   


    select 
    [承接单位],
    count([合同id]) as [合同数量],
    sum([合同金额]) as [总金额],
    sum([拨款金额]) as [总拨款金额],
    sum([合同金额])-sum([拨款金额]) as [剩余金额] 
    from 
    (
    SELECT 
    h表.*,
    sum([拨款金额]) as [拨款金额]  
    FROM h表,m表 
    WHERE h表.[合同id]=m表.[合同id] 
    GROUP BY h表.[合同id],h表.[承接单位],h表.[合同金额]
    ) a
    group by [承接单位]