计算自上次扣除后的年数
Count number of years since last deduction
我有一个类似于下面的 table,其中同一帐户的财政年度 (FY) 和每年的扣除额分为多行。帐户的范围可以从 1 到 20 年以上。我如何分组到一个唯一的行来显示当前年份以及自帐户扣款以来已经过了多少年?
来自这个:
对此:
像过去一样开始使用 CTE 方法,但和以前一样开始变得丑陋,我知道必须有更简单的方法...
假设当前年份是最近的一年,您将使用聚合:
select account, max(fy),
sum(case when fy = max_fy then deductions end) as this_year_deduction,
max(fy) - max(case when deduction < 0 then fy end) as years_since_deduction
from (select t.*, max(fy) over (partition by account) as max_fy
from t
) t
group by account;
注意:我假设第三列是最近的扣除额。该查询使用 window 函数来提取它。
没有使用下面的方法,但我认为它接近于需要的东西。欢迎指正。 (代码未经测试)
with nonZeroes as
(
select * from YourTable where deductions <> 0
)
select Account,
FY,
FY - LAST_VALUE(FY) OVER (PARTITION BY Account
ORDER BY Year Desc
RANGE BETWEEN CURRENT ROW AND UNBOUNDED PRECEDING) AS years_since_deductions
from nonZeroes
我有一个类似于下面的 table,其中同一帐户的财政年度 (FY) 和每年的扣除额分为多行。帐户的范围可以从 1 到 20 年以上。我如何分组到一个唯一的行来显示当前年份以及自帐户扣款以来已经过了多少年?
来自这个:
对此:
像过去一样开始使用 CTE 方法,但和以前一样开始变得丑陋,我知道必须有更简单的方法...
假设当前年份是最近的一年,您将使用聚合:
select account, max(fy),
sum(case when fy = max_fy then deductions end) as this_year_deduction,
max(fy) - max(case when deduction < 0 then fy end) as years_since_deduction
from (select t.*, max(fy) over (partition by account) as max_fy
from t
) t
group by account;
注意:我假设第三列是最近的扣除额。该查询使用 window 函数来提取它。
没有使用下面的方法,但我认为它接近于需要的东西。欢迎指正。 (代码未经测试)
with nonZeroes as
(
select * from YourTable where deductions <> 0
)
select Account,
FY,
FY - LAST_VALUE(FY) OVER (PARTITION BY Account
ORDER BY Year Desc
RANGE BETWEEN CURRENT ROW AND UNBOUNDED PRECEDING) AS years_since_deductions
from nonZeroes