SQL帐户余额表

时间:2016-05-25 18:35:40

标签: sql-server

我有一个程序的运行帐户余额,可根据用户的交易进行更新。从此我想加入一个表,其中包含每个用户的行和程序历史的每个日期,以便我可以了解余额的分布如何随时间变化。

交易余额数据的Ex.1(这是日终余额):

userId  transDate   userBalance
33782   2016-05-13  233
33783   2016-05-13  143
30070   2016-05-20  572
30071   2016-05-20  888

实施例。 2日历表

userID  balanceDate 
33782   2016-05-13 
33783   2016-05-13 
30070   2016-05-13 
30071   2016-05-13 
33782   2016-05-20  
33783   2016-05-20  
30070   2016-05-20  
30071   2016-05-20  

期望的结果

userId  balanceDate userBalance 
33782   2016-05-13  233 
33783   2016-05-13  143 
30070   2016-05-13  0
30071   2016-05-13  0 
33782   2016-05-20  233 
33783   2016-05-20  143 
30070   2016-05-20  572 
30071   2016-05-20  888

基本上我需要以某种方式将事务表连接到calendarBalance表,并让userBalance字段返回最大记录记录,其中transDate小于或等于balanceDate,否则为0。 由于数据库有数百万笔交易,我所做的每一次尝试都会超时。 我正在使用SQL Server 2012。

这是一次超时的尝试:

SELECT d.balanceDate ,b.userId ,b.userBalance 
FROM #calendar d ,#userBalance b 
WHERE d.balanceDate >= b.transDate 
AND b.transDate >= ALL ( 
 SELECT b1.transDate 
 FROM #userBalance b1 
 WHERE b.userId = b1.userId 
 AND d.transDate >= b1.transDate 
) 
ORDER BY d.balanceDate ,b.userId

1 个答案:

答案 0 :(得分:0)

Declare @Transaction table (UserID int,TransDate Date,UserBalance int)
Insert into @Transaction Select 33782,'2016-05-13',233
Insert into @Transaction Select 33783,'2016-05-13',143
Insert into @Transaction Select 30070,'2016-05-20',572
Insert into @Transaction Select 30071,'2016-05-20',888

Declare @Calendar table (UserID int,BalanceDate date)
Insert into @Calendar Select 33782,'2016-05-13'
Insert into @Calendar Select 33783,'2016-05-13' 
Insert into @Calendar Select 30070,'2016-05-13'
Insert into @Calendar Select 30071,'2016-05-13' 
Insert into @Calendar Select 33782,'2016-05-20'  
Insert into @Calendar Select 33783,'2016-05-20'  
Insert into @Calendar Select 30070,'2016-05-20'  
Insert into @Calendar Select 30071,'2016-05-20'  



Select A.*,UserBalance=isnull((Select top 1 UserBalance From @Transaction Where UserID=A.UserID and TransDate<=A.BalanceDate Order by TransDate Desc),0)
 From (
        Select UserID,balanceDate
         From (Select Distinct UserID from @Calendar) U
         Join (Select Distinct balanceDate  from @Calendar) C on 1=1
      ) A
 Order by 2,1 Desc

返回

UserID  balanceDate UserBalance
33783   2016-05-13  143
33782   2016-05-13  233
30071   2016-05-13  0
30070   2016-05-13  0
33783   2016-05-20  143
33782   2016-05-20  233
30071   2016-05-20  888
30070   2016-05-20  572