日期:2014-05-18  浏览次数:20422 次

两个表 求SQL
表1
UserId Capital
1 50
2 60
3 70

表2
UserId Price Vol
1 1.8 50
1 3.6 20
2 2.4 70
3 6.2 10
2 1.3 30

表2要按UserId 去更新表1的Capital。。。。(Capital = Price * Vol)

------解决方案--------------------
SQL code

create table 表1(UserID int,Capital money)
create table 表2(UserID int,Price money,Vol int)
go
insert 表1
select 1,50 union
select 2,60 union
select 3,70

insert 表2

select 1,1.8,50 union
select 1,3.6,20 union
select 2,2.4,70 union
select 3,6.2,10 union
select 2,1.3,30
 


update 表1 set Capital=表1.Capital+b.Capital from (select UserID,SUM(Price*Vol) Capital from 表2 group by UserID)b where 表1.UserID=b.UserID 

 select * from 表1
 /*
 UserID    Capital
1    212.00
2    267.00
3    132.00
*/

drop table 表1
drop table 表2