在 SQL Server 2014 上使用 over 子句运行总计

问题描述

我使用以下 T-sql查询通过 RefId 计算运行总量。

由于我的表有超过 2M 的行,我想使用 OVER 子句重写查询

但我无法得到相同的结果;当 CreationDate 对于 RefId 不是唯一的时,结果不正确,因为将具有相同日期的前一行添加到总和中。

是否有获得正确结果的解决方案?

样本数据集:

CREATE TABLE Command 
(
    CreationDate SMALLDATETIME,RefId INT,Qte INT
);


INSERT INTO Command VALUES('2021-01-10',100,10);
INSERT INTO Command VALUES('2021-01-11',20);
INSERT INTO Command VALUES('2021-01-11',60);
INSERT INTO Command VALUES('2021-01-11',10);
INSERT INTO Command VALUES('2021-01-12',20);
INSERT INTO Command VALUES('2021-01-10',200,20);
INSERT INTO Command VALUES('2021-01-12',10);

具有正确结果的子查询

SELECT 
    c1.*,(SELECT SUM(c2.Qte) 
     FROM Command c2
     WHERE c1.RefId = c2.RefId
       AND c2.CreationDate < c1.CreationDate) AS RunninTotal_Qte
FROM 
    Command c1
ORDER BY 
    c1.RefId,c1.CreationDate

Result Sub-Query

使用 OVER 子句重写查询;结果不正确

SELECT 
    c1.*,SUM(c1.Qte) OVER (PARTITION BY c1.RefId ORDER BY c1.CreationDate 
                      ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS RunningTotal_Qte
FROM 
    Command c1
ORDER BY 
    c1.RefId,c1.CreationDate

enter image description here

解决方法

SELECT c1.*,SUM(c1.Qte) OVER(PARTITION BY c1.RefId ORDER BY c1.CreationDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as RunningTotal_Qte
FROM Command c1
ORDER BY c1.RefId,c1.CreationDate
,

如果必须的话,你已经在做的方式会更高效,这里是如何只使用窗口函数来做到这一点:

# Update PSKeyVaultSecretIdentityItem object type to include scriptproperty secretvaluetext
$Script = { Get-AzKeyVaultSecret -VaultName $this.VaultName -Name $this.Name -AsPlainText }
Update-TypeData -TypeName 'Microsoft.Azure.Commands.KeyVault.Models.PSKeyVaultSecretIdentityItem' -MemberName 'SecretValueText' -MemberType ScriptProperty -Value $Script

# SecretValueText property will contain decrypted secret text for the session
$secret = Get-AzKeyVaultSecret -VaultName 'Contoso' -Name 'ITSecret'
$secret.SecretValueText