我想将发票数据金额转换为每月的实际费用。有什么建议吗?
我有一张这样的桌子:
InvoiceID INVOICE_DATE AMOUNT SplitOnNumberOfMonthToCome
-----------------------------------------------------------------------------
23 2019-12-05 00:00:00.000 3000 3
24 2019-12-07 00:00:00.000 2000 1
25 2020-03-12 00:00:00.000 12000 3
26 2020-03-03 00:00:00.000 5000 1
并想要这个:
InvoiceID MonthPeriod Amount
---------------------------------------
23 202001 1000
23 202002 1000
23 202003 1000
24 202001 2000
25 202004 4000
25 202005 4000
25 202006 4000
26 202004 5000
答案 0 :(得分:2)
您可以使用递归CTE。如果我理解正确:
with cte as (
select invoiceid, invoice_date, amount / num_months as month_amount, 1 as n, num_months
from t
union all
select invoiceid, invoice_date, month_amount, n + 1, num_months
from cte
where n < num_months
)
select inoiceid,
format(dateadd(month, n, invoice_date), 'yyyymm') as monthperiod,
month_amount
from cte;