我有一个问题,我必须使用公式来计算列,该公式使用上一行中计算得出的值。
我尝试了滞后功能,但无法通过第二行。之后,我的所有值都为null,因为该列最初以null开头。我觉得我想念什么。
我需要使用以下公式计算新列:
MovingRate = MonthlyRate + (0.7 * MovingRatePrevious)
...其中MovingRatePrevious
是上一行的MovingRate
。对于第1个月,我具有该值,因此不需要重新计算该值,但是需要该值才能计算后续的行。我需要按类型分区。
这是我的原始数据集:
Month Type MonthyRate MovingRate
--------------------------------------
1 Blue 0.400 0.330
2 Blue 0.300
3 Blue 0.700
4 Blue 0.900
MovingRate
列中所需的结果:
Month Type MonthyRate MovingRate
---------------------------------------
1 Blue 0.400 0.330
2 Blue 0.300 0.531
3 Blue 0.700 1.072
4 Blue 0.900 1.650
答案 0 :(得分:2)
您可以使用递归CTE进行计算。以下是您的数据的通用版本:
DECLARE @t TABLE (Month INT, Type VARCHAR(100), MonthlyRate DECIMAL(18, 3));
INSERT INTO @t VALUES
(1, 'Blue', 0.400),
(2, 'Blue', 0.300),
(3, 'Blue', 0.700),
(4, 'Blue', 0.900);
WITH cte1 AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Month) AS rn
FROM @t
), rcte AS (
SELECT *, CAST(0.330 AS DECIMAL(18, 3)) AS MovingRate
FROM cte1 AS base
WHERE rn = 1
UNION ALL
SELECT curr.*, CAST(curr.MonthlyRate + 0.7 * prev.MovingRate AS DECIMAL(18, 3))
FROM cte1 AS curr
JOIN rcte AS prev ON curr.Type = prev.type AND curr.rn = prev.rn + 1
)
SELECT *
FROM rcte