假设我有以下架构:
-- Create the dbo.Transaction table
CREATE TABLE [dbo].[Transaction] (
[TransactionId] INT NOT NULL IDENTITY,
[AccountId] INT NOT NULL,
[TransactionDate] DateTime2(7) NOT NULL,
[Amount] decimal(9,3) NOT NULL
CONSTRAINT [PK_Transaction] PRIMARY KEY ([TransactionId])
);
以及以下查询:
Select
AccountId,
TransactionDate,
Amount,
AverageAmount = Avg(Amount) Over (Partition By AccountId Order By TransactionDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW),
TransactionCount = Count(Amount) Over (Partition By AccountId Order By TransactionDate ROWS 2 PRECEDING),
MinimumAmount = Min(Amount) Over (Partition By AccountId Order By TransactionDate ROWS 2 PRECEDING),
MaximumAmount = Max(Amount) Over (Partition By AccountId Order By TransactionDate ROWS 2 PRECEDING),
SumAmount = Sum(Amount) Over (Partition By AccountId Order By TransactionDate ROWS 2 PRECEDING)
From dbo.[Transaction]
Order By AccountId, TransactionDate
如果它包含在 UDF 或存储过程中,我将如何执行此查询,并且滑动间隔(在此示例中为 2)直到运行时才知道,作为参数传递给 UDF / 存储过程?似乎 SQL 2012 不允许在此处使用变量。