SQL server 里按年按月进行累计值统计
即 4月 算从1~4月的累计值
参考如下:
select dt,
account_set_ord,
account_set_title,
account_ord,
account_title,
year,
ym,
cumulative_money_J,
cumulative_money_D,
row_num
from (
SELECT
dt,
account_set_ord,
account_set_title,
account_ord,
account_title,
year,
ym,
cumulative_money_J,
cumulative_money_D,
ROW_NUMBER() OVER (PARTITION BY account_set_ord, account_set_title, account_ord, account_title, year, ym,cumulative_money_J, cumulative_money_D ORDER BY ym) as row_num
from (
SELECT
@DateThreshold as dt,
account_set_ord,
account_set_title,
account_ord,
account_title,
year,
ym,
SUM(income_money) OVER (PARTITION BY account_set_ord, account_set_title, account_ord, account_title, year ORDER BY ym) AS cumulative_money_J,
SUM(expense_money) OVER (PARTITION BY account_set_ord, account_set_title, account_ord, account_title, year ORDER BY ym) AS cumulative_money_D
FROM dws_finance_fund_balance_income_expense_month
WHERE dt = @DateThreshold
) t1
) t4
where t4.row_num = 1
采用 SUM(expense_money) OVER (PARTITION BY account_set_ord, account_set_title, account_ord, account_title, year ORDER BY ym) 来计算累计值
通过 ROW_NUMBER() OVER (PARTITION BY account_set_ord, account_set_title, account_ord, account_title, year, ym,cumulative_money_J, cumulative_money_D ORDER BY ym) as row_num 来进行过滤
INSERT INTO dbo.dws_finance_fund_balance_month ([dt],[year],[quarter],[ym],[account_set_ord],[account_set_title],[account_ord],[account_title],[income_money],[cumulative_income_money],[expense_money],[cumulative_expense_money])SELECT t1.[dt],t1.[year],t1.[quarter],t1.[ym],t1.[account_set_ord],t1.[account_set_title],t1.[account_ord],t1.[account_title],t1.[income_money],t2.cumulative_money_J,t1.[expense_money],t2.cumulative_money_Dfrom ( select [dt],[year],[quarter],[ym],[account_set_ord],[account_set_title],[account_ord],[account_title],[income_money],[expense_money]from dbo.dws_finance_fund_balance_income_expense_month where dt = @DateThreshold)t1left join (select dt,account_set_ord, account_set_title, account_ord,account_title,year,ym,cumulative_money_J,cumulative_money_D,row_numfrom ( SELECT dt,account_set_ord, account_set_title, account_ord,account_title,year,ym,cumulative_money_J,cumulative_money_D,ROW_NUMBER() OVER (PARTITION BY account_set_ord, account_set_title, account_ord, account_title, year, ym,cumulative_money_J, cumulative_money_D ORDER BY ym) as row_numfrom ( SELECT @DateThreshold as dt,account_set_ord, account_set_title, account_ord,account_title,year,ym,SUM(income_money) OVER (PARTITION BY account_set_ord, account_set_title, account_ord, account_title, year ORDER BY ym) AS cumulative_money_J,SUM(expense_money) OVER (PARTITION BY account_set_ord, account_set_title, account_ord, account_title, year ORDER BY ym) AS cumulative_money_D FROM dws_finance_fund_balance_income_expense_monthWHERE dt = @DateThreshold) t1) t4where t4.row_num = 1) t2on t1.account_set_ord = t2.account_set_ord and t1.account_ord = t2.account_ord and t1.year = t2.year and t1.ym = t2.ym