0

我有一个将余额历史存储在历史表中的系统。该表有帐号、排序代码、余额、余额开始日期、余额结束日期。当余额更新时,会在历史表中创建一个条目,其中显示余额、余额首次开始的日期以及显示余额更改的日期。例如,该表将显示 100.00 美元的余额,该余额从 2013 年 7 月 10 日到 2013 年 7 月 15 日。

我想要做的是在特定日期获取所有排序代码的余额总和,但是余额可能在这个日期没有改变,所以我需要返回最接近的前一个日期,但我失败了。

这是我到目前为止所尝试的。

declare @sdate datetime
set @sdate = '06/08/2012' --mm/dd/yyyy

SELECT CONVERT(varchar(20),MAX(StartDate),103) as "Closest Start Date",  Sort, SUM(Balance) AS "Sum of balances"
    FROM BalanceHistory
        WHERE StartDate <= convert(smalldatetime ,@sdate) AND SortCode <> 'ABC123456'
            GROUP BY SortCode

SELECT FROM BalanceHistory 会产生类似

AccountNumber, SortCode, Balance, StartDate, EndDate, RECID
00000001, srt010203, 100.00, 06/01/2013, 06/02/2013,  RECID
00000001, srt010203, 110.00, 06/02/2013, 06/03/2013,  RECID
00000001, srt010203, 120.00, 06/03/2013, 06/04/2013,  RECID
00000002, srt010204, 200.00, 06/01/2013, 06/02/2013,  RECID
00000003, srt010204, 300.00, 06/01/2013, 06/02/2013,  RECID
00000004, srt010205, 400.00, 06/01/2013, 06/02/2013,  RECID
00000005, srt010205, 500.00, 06/01/2013, 06/02/2013,  RECID
4

2 回答 2

1

您可以在不JOIN使用ROW_NUMBER()函数的情况下执行此操作(假设 SQL Server 2005 或更高版本):

DECLARE @sdate DATE
SET @sdate = '2012-06-08'
SELECT SortCode, SUM(Balance)'Sum of Balances'
FROM (SELECT AccountNumber,SortCode, Balance,ROW_NUMBER() OVER (PARTITION BY AccountNumber ORDER BY StartDate DESC)'RowRank'
        FROM BalanceHistory
        WHERE StartDate <= @sdate AND SortCode <> 'ABC123456'
     )sub
WHERE RowRank = 1
GROUP BY SortCode

演示:SQL 小提琴

子查询中的ROW_NUMBER()函数为每个帐号的余额分配一个“RowRank”,我们按 StartDate DESC 排序以获得每个帐号最近余额的“1”排名,WHERE 条件将其限制为该日期的最近余额你在你的变量中设置。然后,您在外部查询中使用该排名以仅限制该余额。

于 2013-07-16T16:21:37.830 回答
0

这应该工作

Declare @table as table
(AccountNo int,
 Balance money,
 DateEntered datetime)

 Declare @dt datetime

 set @dt = '2013-07-01'
 Insert into @table values(1, 100, '2013-04-01')
Insert into @table values(2, 200, '2013-04-01')
Insert into @table values(2, 300, '2013-05-01')
Insert into @table values(2, 400, '2013-06-01')
  --select AccountNo, Max(Balance), Max(DateEntered) MaxDateEntered From @table where DateEntered <= @dt  group by AccountNo 


Select Sum(t.Balance) From @table t
inner join (select AccountNo, Max(Balance) Balance, Max(DateEntered) MaxDateEntered From @table where DateEntered <= @dt  group by AccountNo) tm
on t.AccountNo = tm.AccountNo and t.DateEntered = tm.MaxDateEntered

    enter code here
于 2013-07-16T16:16:38.363 回答