TableX
带有列和值
A B C D E F G H Level
---------------------------------------------------------------------
10 ABC 10 ABC XYZ 2 3 4 1
10 ABC 10 ABC XYZ 2 3 4 1
11 DEF 10 ABC XYZ 4 5 6 2
11 DEF 10 ABC XYZ 6 7 8 2
12 GHI 11 DEF XYZ 7 8 9 3
12 GHI 11 DEF XYZ 8 9 10 3
15 JKL 15 JKL ABC 9 10 11 1
15 JKL 15 JKL ABC 10 11 12 1
16 MNO 15 JKL ABC 13 14 15 2
16 MNO 15 JKL ABC 16 16 18 2
这里Level
不是表格中的一列,我只是为了清楚起见而添加,但 CTE 会通过将 A、B 与 C 和 D 进行比较来自动推断
对于 1 级,计算将是
Calc1 = (F + G - H)
Calc2 = Calc1 + G + H
2级及以后的计算公式为
Calc1 = (Calc2 Of Previous Level) 的总和 / 100
Calc2 = Calc1 + G + H - 无论级别如何,此计算都没有变化
The calculation is cyclic
- 2 级的计算结果将需要输入到 3 级计算等等..
WITH Tiers (
Level,
A,
B,
C,
D,
E,
Calc1,
Calc2)
AS
SELECT 1 AS Level,
A,
B,
C,
D,
E,
F + G - H AS Calc1,
(F + G - H) + G + H AS Calc2
FROM TableX
WHERE A = C
AND B = D
UNION ALL
SELECT tier.Level + 1 AS Level,
A,
B,
C,
D,
E,
/* How can I do this SUM (tier.Calc1) / 100 */
/* How can I do this SUM (tier.Calc1) / 100 + G + H */
FROM TableX tab
INNER JOIN Tiers tier
ON tab.C = tier.A
AND tab.D = tier.B
AND tab.E = tier.E
WHERE (A <> C
OR B <> D)
)
SELECT *
FROM Tiers
我试过了
SELECT tier.Level + 1 AS Level,
A,
B,
C,
D,
E,
sumCalc.calc1 / 100 Calc1
sumCalc.calc1 / 100 + G + H Calc2
FROM TableX tab
INNER JOIN Tiers tier
ON tab.C = tier.A
AND tab.E = tier.B
INNER JOIN (
SELECT A, B, E, SUM(Calc1) Calc1
FROM Tiers
GROUP BY A, B, E) sumCalc /* SQL Server throws error that CTE table cannot be used here */
WHERE (A <> C
OR B <> D)
我也希望使用表值的 OUTER APPLY 或其他东西..