select 项目编号=a.项目编号,项目名称=a.项目名称,项目所有合同的金额=b.合同金额,
项目所有合同已付款金额=c.付款金额
from 项目 a inner join 合同 b
on a.项目编号=b.项目编号
inner join 付款 c
on b.合同编号=c.合同编号
项目所有合同已付款金额=c.付款金额
from 项目 a inner join 合同 b
on a.项目编号=b.项目编号
inner join 付款 c
on b.合同编号=c.合同编号
select *, (select sum(付款金额) from 付款 where 付款.合同编号 = 合同.合同编号) from 合同
我要这个效果,谢谢
,项目所有合同的金额=sum(b.合同金额)
,项目所有合同已付款金额=sum(c.付款金额)
from 项目 a,合同 b,付款 c
where a.项目编号=b.项目编号
and b.合同编号=c.合同编号
group by a.项目编号,a.项目名称
列 'c.付款金额' 在选择列表中无效,因为该列既不包含在聚合函数中,也不包含在 GROUP BY 子句中。
from
(select A.项目编号,A.项目名称,项目所有合同的金额=sum(B.合同金额)
from 项目 A LEFT JOIN 合同 B ON A.项目编号=B.项目编号
group by A.项目编号,A.项目名称) L
JOIN
(select B.项目编号, 项目所有合同已付款金额=sum(付款金额)
from 合同 B LEFT JOIN 付款 C ON B.合同编号=C.合同编号
group by B.项目编号) RON L.项目编号=R.项目编号
select a.项目编号,a.项目名称
,项目所有合同的金额=sum(b.合同金额)
,项目所有合同已付款金额=sum(c.付款金额)
from 项目 a left join 合同 b on a.项目编号=b.项目编号
left join (
select 合同编号,sum(合同金额) 合同金额 from 付款 group by 合同编号
) c on b.合同编号=c.合同编号
group by a.项目编号,a.项目名称
declare @项目 table(项目编号 int,项目名称 char(6))
insert @项目
select 1,'项目1'
insert @项目
select 2,'项目2'
insert @项目
select 3,'项目3'declare @合同 table(合同编号 int ,项目编号 int,合同金额 int)
insert @合同
select
1, 1, 10.00
insert @合同
select
2, 1, 5.00
insert @合同
select
3, 2, 15.00
declare @付款 table(付款编号 int, 合同编号 int ,付款金额 int)
insert @付款
select
1, 1, 1.0
insert @付款
select
2, 2, 2.0
insert @付款
select
3, 2, 3.0select a.*,
isnull(sum(b.合同金额),0) 合同金额,
isnull(sum(c.付款金额),0) 付款金额
from @项目 a left join @合同 b on a.项目编号 = b.项目编号
left join (
select 合同编号, sum(付款金额) 付款金额 from @付款 group by 合同编号
) c on b.合同编号 = c.合同编号
group by a.项目编号,a.项目名称
/*
项目编号 项目名称 合同金额 付款金额
----------- ------ ----------- -----------
1 项目1 15 6
2 项目2 15 0
3 项目3 0 0(所影响的行数为 3 行)
*/
insert into @项目
select 1,'项目1' union all
select 2,'项目2' union all
select 3,'项目3'
declare @合同 table(合同编号 int,项目编码 int,合同金额 decimal(28,2))
insert into @合同
select 1,1,10.00 union all
select 2,1,5.00 union all
select 3,2,15.00
declare @付款 table(付款编号 int,合同编号 int,付款金额 decimal(28,2))
insert into @付款
select 1,1,1.00 union all
select 2,2,2.00 union all
select 3,2,3.00select t.项目编码,t.项目名称,t.项目所有合同的金额,项目所有合同已付款金额=sum(项目所有合同已付款金额) from (select a.*,项目所有合同的金额=isnull(b.项目所有合同的金额,0),项目所有合同已付款金额=isnull(c.项目所有合同已付款金额,0) from @项目 a left join (select 项目编码,项目所有合同的金额=sum(合同金额) from @合同 group by 项目编码)b on a.项目编码=b.项目编码 left join @合同 b1 on a.项目编码=b1.项目编码 left join (select 合同编号,项目所有合同已付款金额=sum(付款金额)from @付款 group by 合同编号)c on b1.合同编号=c.合同编号 )t group by t.项目编码,t.项目名称,t.项目所有合同的金额
from a,(select sum(合同金额),项目编号 from b group by 项目编号)as bb,
( select b.项目编号,sum(c.付款金额) from c,b where c.合同编号= b.合同编号 group by b.项目编号 group by b.项目编号) as cc where a.项目编号=bb.项目编号 and bb.项目编号=cc.项目编号