表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文
合同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文
解决方案 »
- 简单的问题,这个SQL语句怎么写?
- SQL Server2008关于字符串截取的问题
- 调试存储过程没有问题,asp.net调用却出错..
- 看似简单的问题!
- select round(5.0/10.2,1) 的值是0.5,为什么select str(round(5.0/10.2,1))+'%'的值是 1%,我怎么才能得到 0.5%
- 帮忙解决错误 '80004005',Optional feature not implemented
- 一个用update 不能解决的问题,
- 请问一个SQL查询语句的问题
- 一个存储过程A 中调用另一个存储过程B,请问如何得到或者访问 B所返回的结果集?
- 创建临时表出错!!
- 大家帮给看一下这个语句怎么改
- update 遇到问题,提示如下:
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.承建单位
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.承建单位
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 承接单位
(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.承建单位
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 [承接单位]