我有一个在Azure SQL Server上定义如下的表:
CREATE TABLE dbo.[transaction]
(
id INT IDENTITY(1,1) NOT NULL,
[date] DATETIME NULL,
amount FLOAT NULL,
balance FLOAT NULL,
account_id INT NULL,
CONSTRAINT PK__transact__32F PRIMARY KEY (id)
)
我想找到某个日期之前每个帐户的最后余额。我需要返回的列是:account_id,日期,余额。
我尝试过:
select account_id, max(date) as date
from dbo.[transaction]
group by account_id
这有效,但不会退还余额。
第二,我的交易首先按日期排序,然后按ID排序。因此,如果在最大日期发生多次交易,则应选择ID最高的交易余额。
我的应用程序是用flask-sqlalchemy编写的,因此sqlalchemy的答案会很好,但我也对SQL的答案感到满意。
答案 0 :(得分:2)
您可以使用row_number
窗口函数为每个帐户ID的行编号,并为每个帐户获取最后一行:
SELECT account_id, [date], balance
FROM (SELECT account_id, [date], balance,
ROW_NUMBER() OVER (PARTITION BY account_id
ORDER BY [date] DESC, id DESC) AS rn
FROM [transaction]) t
WHERE rn = 1
答案 1 :(得分:1)
解决方案:包括日期检查
CREATE TABLE #transaction (
id int NOT NULL,
[date] datetime NULL,
amount float NULL,
balance float NULL,
account_id int NULL
) ;
Insert Into #transaction Values
(1,'2018-11-20',50,4000,100),
(2,'2018-11-21',75,2475,100),
(3,'2018-12-15',75,2400,100),
(4,'2018-11-22',25,4000,200),
(5,'2018-11-22',25,4000,300)
With CTE As
(
Select
ROW_NUMBER() Over(Partition By account_id Order By [Date] Desc) As rn,
account_id, [Date], balance
From #transaction
Where [Date] < '2018-12-01'
)
Select account_id, [Date], balance From CTE
Where rn = 1
结果:
account_id Date balance
100 2018-11-21 00:00:00.000 2475
200 2018-11-22 00:00:00.000 4000
300 2018-11-22 00:00:00.000 4000
答案 2 :(得分:0)
提供的答案同样出色。
我已将其转换为python sqlalchemy答案以供参考:
fscanf
最后三行可选内容将其转换为带有期初余额的熊猫数据框,按日期和ID排序。