如何解决此LAG声明中的循环引用?

时间:2018-11-08 20:00:21

标签: sql-server sql-server-2012

我需要使用LAG来获取最后一行的EndingUnits值,并将其用作当前行的OpeningUnits。问题的部分原因是我无法在定义别名的select语句中使用任何别名,例如EndingUnitsOpeningUnits。另一个问题是EndingUnits的定义依赖于OpeningUnits,而EndingUnits本身受DividendPricing依赖。

涉及的唯一表是DividendPricingID PK, int FiscalPeriod smalldatetime DivPrice money DivFactor float ,它看起来像这样:

OpeningUnits = LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod)
DRIP = (LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod))/DivPrice*DivFactor
EndingUnits = OpeningUnits + DRIP

-

SELECT FiscalPeriod,
    LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod) AS OpeningUnits,
    DivPrice,
    DivFactor,
    LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod)/DivPrice*DivFactor AS [DRIP],
    LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod) + (LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod)/DivPrice*DivFactor) AS EndingUnits
    FROM DividendPricing

我的查询如下所示,但显然不起作用:

{{1}}

1 个答案:

答案 0 :(得分:0)

我并不真正理解您期望的结果,但是,要以您希望的方式使用LAG(),则必须从起点开始进行。我使用CTE整理了这个示例,也许可以帮助您找到理想的解决方案。

DECLARE @T TABLE(FiscalPeriod SMALLDATETIME,DivPrice MONEY,DivFactor FLOAT)
INSERT @T VALUES
    ('01/01/2012',2,1.2),('04/01/2012',4,1.23),('07/01/2012',6,1.1),('10/01/2012',8,1.15),
    ('01/01/2013',2,1.2),('04/01/2013',4,1.23),('07/01/2013',6,1.1),('10/01/2013',8,1.15)

;WITH Start AS
(
    SELECT 
        EndingUnits = 1, FiscalPeriod,DivPrice, DivFactor 
    FROM 
        @T       
)
,NormalizedEnding AS
(
    SELECT 
        FiscalPeriod, DivPrice, DivFactor,
        EndingUnits = LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod) + (LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod) / DivPrice * DivFactor) 
    FROM 
        Start 
),
ContinuationCalulation AS
(
    SELECT
        FiscalPeriod,DivPrice,DivFactor,
        OpeningUnits =  LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod),
        DRIP = (LAG(EndingUnits, 1, 1) OVER (ORDER BY FiscalPeriod))/DivPrice*DivFactor,
        x=EndingUnits
    FROM
        NormalizedEnding
)
SELECT
    FiscalPeriod,DivPrice,DivFactor,OpeningUnits,
    EndingUnits = OpeningUnits + DRIP,
    x
FROM
    ContinuationCalulation