SQL 将先前的行余额除以当前行余额并将该值插入当前行列 "Growth"
SQL Divide previous row balance by current row balance and insert that value into current rows column "Growth"
我有一个 table 这样的地方。
Year
ProcessDate
Month
Balance
RowNum
Calculation
2022
20220430
4
22855547
1
2022
20220330
3
22644455
2
2022
20220230
2
22588666
3
2022
20220130
1
33545444
4
2022
20221230
12
22466666
5
我需要用每一列的前一行除以当前行。
例如:第 1 行计算应 = 第 2 行余额/第 1 行余额 (22644455/22855547 = .99%)
第 2 行计算应 = 第 3 行余额/第 2 行余额等....
Table 只是我创建的临时 table 标题为 #MonthlyLoanBalance2。
现在我只需要更进一步。
让我知道你会做什么以及如何去做。
提前致谢!
Insert into #MonthlytLoanBalance2 (
Year
,ProcessDate
,Month
,Balance
,RowNum
)
select
--CloseYearMonth,
left(ProcessDate,4) as 'Year',
ProcessDate,
--x.LOANTypeKey,
SUBSTRING(CAST(x.ProcessDate as varchar(38)),5,2) as 'Month',
sum(x.currentBalance) as Balance
,ROW_NUMBER()over (order by ProcessDate desc) as RowNum
from
(
select
distinct LoanServiceKey,
LoanTypeKey,
AccountNumber,
CurrentBalance,
OpenDateKey,
CloseDateKey,
ProcessDate
from
cu.LAFactLoanSnapShot
where LoanStatus = 'Open'
and LoanTypeKey = 0
and ProcessDate in (select DateKey from dimDate
where IsLastDayOfMonth = 'Y'
and DateKey > convert(varchar, getdate()-4000, 112)
)
) x
group by ProcessDate
order by ProcessDate desc;``
我假设您的数据已经准备好,如 table 中所示。现在您可以尝试 Lead() 函数来解决您的问题。请记住 format() 函数仅用于取两个精度。
SELECT *,
FORMAT((ISNULL(LEAD(Balance,1) OVER (ORDER BY RowNum), 1)/Balance),'N2') Calculation
FROM #MonthlytLoanBalance2
我有一个 table 这样的地方。
Year | ProcessDate | Month | Balance | RowNum | Calculation |
---|---|---|---|---|---|
2022 | 20220430 | 4 | 22855547 | 1 | |
2022 | 20220330 | 3 | 22644455 | 2 | |
2022 | 20220230 | 2 | 22588666 | 3 | |
2022 | 20220130 | 1 | 33545444 | 4 | |
2022 | 20221230 | 12 | 22466666 | 5 |
我需要用每一列的前一行除以当前行。
例如:第 1 行计算应 = 第 2 行余额/第 1 行余额 (22644455/22855547 = .99%) 第 2 行计算应 = 第 3 行余额/第 2 行余额等....
Table 只是我创建的临时 table 标题为 #MonthlyLoanBalance2。 现在我只需要更进一步。 让我知道你会做什么以及如何去做。 提前致谢!
Insert into #MonthlytLoanBalance2 (
Year
,ProcessDate
,Month
,Balance
,RowNum
)
select
--CloseYearMonth,
left(ProcessDate,4) as 'Year',
ProcessDate,
--x.LOANTypeKey,
SUBSTRING(CAST(x.ProcessDate as varchar(38)),5,2) as 'Month',
sum(x.currentBalance) as Balance
,ROW_NUMBER()over (order by ProcessDate desc) as RowNum
from
(
select
distinct LoanServiceKey,
LoanTypeKey,
AccountNumber,
CurrentBalance,
OpenDateKey,
CloseDateKey,
ProcessDate
from
cu.LAFactLoanSnapShot
where LoanStatus = 'Open'
and LoanTypeKey = 0
and ProcessDate in (select DateKey from dimDate
where IsLastDayOfMonth = 'Y'
and DateKey > convert(varchar, getdate()-4000, 112)
)
) x
group by ProcessDate
order by ProcessDate desc;``
我假设您的数据已经准备好,如 table 中所示。现在您可以尝试 Lead() 函数来解决您的问题。请记住 format() 函数仅用于取两个精度。
SELECT *,
FORMAT((ISNULL(LEAD(Balance,1) OVER (ORDER BY RowNum), 1)/Balance),'N2') Calculation
FROM #MonthlytLoanBalance2