【发布时间】:2020-08-20 11:20:40
【问题描述】:
我需要在 SQL Server 中创建一个派生列 ColumnC。规则是 ColumnC 的第一行是 ColumnA 和 ColumnB 的乘积。以下行是ColumnC中上一行的乘积,按年份乘以ColumnA * ColumnC。
+-----------+--------------------------+------------------------+
| **Year** | **ColumnA** | **ColumnB** |
+-----------+--------------------------+------------------------+
| 2020 | 0.987441 | 0.001039 |
+-----------+--------------------------+------------------------+
| 2021 | 0.975952 | 0.001117 |
+-----------+--------------------------+------------------------+
| 2022 | 0.965471 | 0.001206 |
+-----------+--------------------------+------------------------+
| 2023 | 0.955950 | 0.001293 |
+-----------+--------------------------+------------------------+
| 2024 | 0.947347 | 0.001387 |
+-----------+--------------------------+------------------------+
| 2025 | 0.939604 | 0.001488 |
+-----------+--------------------------+------------------------+
| 2026 | 0.933461 | 0.001596 |
+-----------+--------------------------+------------------------+
| 2027 | 0.922700 | 0.001710 |
+-----------+--------------------------+------------------------+
| 2028 | 0.914439 | 0.001959 |
+-----------+--------------------------+------------------------+
| 2029 | 0.900277 | 0.002134 |
+-----------+--------------------------+------------------------+
为了保持示例简单,我简化了计算和表格,因此,我需要按照描述计算列。
遵守以下算法对我来说很重要:ColumnC 的第一行是 ColumnA abd ColumnB 的乘积,接下来的行,从第二行开始,使用 ColumnC 的前一行,按 Year × ColumnB × ColumnC 排序。
让我陷入困境的最大问题是我不知道如何获取 ColumnC 的先前值。我不能使用LAG,因为该列还不存在。
SELECT
ColumnA,
ColumnB,
/* First row okay. But the following rows should
use the previous value of ColumnC times ColumnA times ColumnB
that is ColumnC(Year-1) * ColumnA * ColumnB
CASE WHEN ROW_NUMBER() OVER (ORDER BY Year) = 1 THEN
ColumnA * ColumnB
ELSE
LAG(ColumnC) OVER (ORDER BY Year) * ColumnA * ColumnB
END AS ColumnC
*/
(ColumnA * ColumnB) AS ColumnC
FROM TableA
这行不通:
CASE WHEN ROW_NUMBER() OVER (ORDER BY Year ASC) = 1 THEN
ColumnA * ColumnB
ELSE
LAG(ColumnC) OVER (ORDER BY Year ASC) * ColumnA * ColumnB
END AS ColumnC
请帮助我理解我的问题。
从ColumnC计算第一行:
从 ColumnC 的第二行开始计算:
结果:
【问题讨论】:
-
编辑您的问题并显示您想要的结果。
-
谢谢,戈登!我编辑了问题并在 Google 表格中添加了结果和示例。我也会测试你的解决方案。
标签: sql sql-server