累計數據的SQL寫法

在常常會用到累計數據的分析,例如:歷史累計量,按年累計量,按月計算累計量,按周計算累計量。
下面是一個通過分析函數來實現的累計數據分析:
歷史累計: 是最容易的,直接用一個分析函數:
語法:sum(XX) over (partition by country order by date) 這個函數的意思是指: 對XX這個指標在country的分組,並且在date的順序進行做累計數據計算
例如:

select t.date_id, t.country_id, t.platform_id,t.newuser, sum(t.newuser) over(partition by t.country_id, t.platform_id order by t.date_id) as totaluser_history from BROWSER_USE_OS_F t where t.date_id>=20130101 and t.country_id=2 and t.platform_id=4

row date_id country_id platform newuser totaluser_history
1 20130101 2 4 13262 13262
2 20130102 2 4 15553 28815
3 20130103 2 4 16418 45233
4 20130104 2 4 16524 61757
5 20130105 2 4 17093 78850
6 20130106 2 4 16316 95166
7 20130107 2 4 15965 111131
8 20130108 2 4 16496 127627
9 20130109 2 4 17185 144812
10 20130110 2 4 16770 161582
按年累計: 這種可以演化推廣到周累計,月累計,季累計等等。
語法:
sum(t.newuser) over(partition by t.country_id, t.platform_id order by t.date_id  rows between to_date(date_id,'yyyy-mm-dd')-to_date(substr(date_id,0,4)||'0101','yyyy-mm-dd') preceding  and current row) as totaluseryesr


這個語句看起來複雜,其實可以其實也簡單,就是在原來的基礎上添加了 rows between 1 preceding and current row 這種樣式的內容,添加了窗口,並且這個窗口的數據區間是跟據時間來變化的。
to_date(date_id,'yyyy-mm-dd')-to_date(substr(date_id,0,4)||'0101','yyyy-mm-dd')
這一行的意思是,計算當前年到當前數據一共有多少行,通過行數來計算。

row between XX preceding and XX following 樣式的類容詳細總結如下:

range between unbounded preceding and current row 指定計算當前行開始、當前行之前的所有值;

rows between 1 preceding and current row 指定計算當前行的前一行開始,其範圍一直延續到當前行;

range between current row and unbounded following 指定計算從當前行開始,包括它後面的所有行;

rows between current row and 1 following 指定計算當前行和它後面的一行;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章