WHILE循环在SQL中

Chr*_*ein 2 sql t-sql

我有两个表:Holdings和Transactions

控股数据如下:

06/30/2009, A, 100
06/30/2009, B, 1200
06/30/2009, C, 100
06/30/2009, D, 100

交易数据如下:

A, 06/05/2009, 100
B, 06/02/2009, 400
B, 06/13/2009, 400
B, 06/28/2009, 400
C, 06/17/2009, 100
D, 06/30/2009, 100

我需要完成的是通过馆藏表并对单独存在的交易进行计算.

我能够将所有事务放入临时表并使用WHILE循环来处理它们.

declare @count int,
        @loopcount int
declare @tblTransactions TABLE
(
ID int identity(1,1),
trtype varchar(10),
trdate datetime,
trvalue int
)
insert into @tblTransactions
select * from Transactions
select @count=@@rowcount
set @loopcount=1
WHILE @loopcount<=count
BEGIN
     select * from @tblTransactions where ID=@loopcount
     set @loopcount=@loopcount+1
END
Run Code Online (Sandbox Code Playgroud)

这一切都非常好,但问题是:如果同一个持有,trtype列有多个交易,我需要计算' trvalue'的总计.

不确定如何在不进行第二次循环的情况下执行此操作.

救命?

And*_*mar 6

你试过加入吗?喜欢:

select <yourcalculation>
from holdings h
left join transactions t on h.holdingid = t.holdingid
Run Code Online (Sandbox Code Playgroud)

如果您只对多个事务感兴趣,则可以使用GROUP BY:

select h.name, sum(t.trvalue)
from holdings h
left join transactions t on h.holdingid = t.holdingid
group by h.holdingid
Run Code Online (Sandbox Code Playgroud)