最近做數(shù)據(jù)模型時發(fā)現(xiàn)一個需要計算數(shù)據(jù)本年累計的一個需求,下面記錄下:
如下圖,需要計算每個人的本年累計和。
原始數(shù)據(jù)
這時候可以利用sql的一個分析函數(shù)來實現(xiàn)累計數(shù)據(jù)分析。
分析函數(shù):sum(XX) over (partition by country order by date) 這個函數(shù)的意思是指: 對XX這個指標(biāo)在country的分組,并且在date的順序進(jìn)行做累計數(shù)據(jù)計算。
例如用上面的原始數(shù)據(jù)寫個sql:
select id,date,name,value,sum(value) over (partition by substr(date,1,4),name order by date) as sumValue from table
執(zhí)行這條語句的結(jié)果如下:
這樣就實現(xiàn)了累計的效果!!