2019 年 10 月 8 日更新:
@Gordon Linoff:我尝试应用您的解决方案,但我意识到它没有按预期工作。我在此处添加了一个带有预期结果的示例(https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=1b486476d6aeab25997f25e66ee455e9),如果您能帮助我,我将不胜感激。
--
我有一个带有架构的事务表:
CREATE TABLE Transactions (Id int IDENTITY, SessionId int, TransactionType varchar(50), DateTimeEnd datetime, DateStart datetime, Rank int);
以下是一些行示例:
INSERT INTO Transactions (Id, SessionId, TransactionType, DateTimeEnd, DateStart, Rank)
VALUES
(1, 1, 'Deposit', '2017-01-20T11:16:33Z', '2017-01-20T11:16:33Z', 600),
(2, 1, 'Withdrawal', '2017-01-21T11:16:33Z', '2017-01-20T11:16:33Z', 100),
(3, 2, 'Deposit', '2017-02-23T11:16:33Z', '2017-02-23T11:16:33Z', 500),
(4, 1, 'Withdrawal', '2017-01-24T11:16:33Z', '2017-01-21T11:16:33Z', 150),
(5, 1, 'Withdrawal', '2017-01-26T11:16:33Z', '2017-01-24T11:16:33Z', 150),
(6, 2, 'Withdrawal', '2017-02-27T11:16:33Z', '2017-02-23T11:16:33Z', 200),
(7, 1, 'Withdrawal', '2017-01-28T11:16:33Z', '2017-01-26T11:16:33Z', 10),
(8, 1, 'Withdrawal', '2017-01-30T11:16:33Z', '2017-01-28T11:16:33Z', 10),
(9, 1, 'Withdrawal', '2017-01-31T11:16:33Z', '2017-01-30T11:16:33Z', 10);
我想要的是一个 T-SQL 查询,用于按 SessionId、TransactionType 和每个组合并连续行组,以仅保留具有最小 DateTimeEnd 的行。此外,保留的行的 Rank 值必须是来自组的行的 Rank 值的总和。T-SQL 查询需要在 Microsoft Azure SQL 数据仓库的 MS SQL Server 中运行。
期望的结果:
| Id | SessionId | Transaction | DateTimeEnd | DateStart | Rank |
|----------|------------------|-------------|--------------------|--------------------|---------|
| 1 | 1 | Deposit|2017-01-20T11:16:33Z|2017-01-20T11:16:33Z| 600 |
| 2 | 1 | Withdrawal|2017-01-21T11:16:33Z|2017-01-20T11:16:33Z| 100 |
| 4 | 1 | Withdrawal|2017-01-24T11:16:33Z|2017-01-21T11:16:33Z| 300 |
| 7 | 1 | Withdrawal|2017-01-28T11:16:33Z|2017-01-26T11:16:33Z| 30 |
| 3 | 2 | Deposit|2017-02-23T11:16:33Z|2017-02-23T11:16:33Z| 500 |
| 6 | 2 | Withdrawal|2017-02-27T11:16:33Z|2017-02-23T11:16:33Z| 200 |
我尝试了很多方法,但无法实现。