34,594
社区成员
发帖
与我相关
我的任务
分享
create table #temp
(
id int not null,
cost1 float not null,
cost2 int not null,
)
select id,sum(cost1),sum(cost2)
from B
group by id
into #temp
select A.id,A.name,A.type sum(#temp.cost1+#temp.cost2)
from A inner join #temp on A.id=#temp.id
select a.*,cost=sum(b.cost1+b.cost2)
from a,b where a.id=b.id
group by a.id,a.name,a.type
Create table #a(
id int,
[name] varchar(10),
[type] varchar(10)
)
insert into #a
select 1,'a','b' union all
select 2,'b','d'
create table #b(
id int,
cost1 float,
cost2 float
)
insert into #b
select 1,23.5,10 union all
select 1,22,12 union all
select 1,33,10 union all
select 2,23,15 union all
select 2,45,16
--原表--
#a
1 a b
2 b d
#b
1 23.5 10
1 22 12
1 33 10
2 23 15
2 45 16
select a.id,a.[Name],a.[Type],b.cost
from (select id,sum(cost1*cost2) cost
from #b
group by id) b left join #a a on b.id=a.id
--结果---
1 a b 829
2 b d 1065
select a.id,a.name,a.type,b.cost
from a,
(select id,sum(cost1+cost2) cost from b where id=1 group by id) b
whre a.id=b.id
select id,name,type,(select sum(cost1+cost2))as cost
from a inner join b
where a.id=b.id
if object_id('[A]') is not null drop table [A]
go
create table [A]([id] int,[name] varchar(1),[type] varchar(1))
insert [A]
select 1,'a','d' union all
select 2,'b','d'
if object_id('[b]') is not null drop table [b]
go
create table [b]([id] int,[cost1] numeric(3,1),[cost2] int)
insert [b]
select 1,23.5,10 union all
select 1,22,12 union all
select 1,33,10 union all
select 2,23,15 union all
select 2,45,16
select a.* , b.cost
from A a inner join
(select id , sum(cost1 + cost2) as cost from b group by id)b
on a.id = b.id
--> 测试数据:@A
declare @A table([id] int,[name] varchar(100),[type] varchar(100))
insert @A
select 1,'a','d' union all
select 2,'b','d'
--> 测试数据:@B
declare @B table([id] int,[cost1] numeric(3,1),[cost2] int)
insert @B
select 1,23.5,10 union all
select 1,22,12 union all
select 1,33,10 union all
select 2,23,15 union all
select 2,45,16
select a.id,sum(cost1+cost2) as total from @A a inner join @B b on a.id = b.id where a.id = '1' group by a.id
/*
id total
----------- ----------------------------------------
1 110.5
(1 row(s) affected)
*/