1
當我執行下面的SQL查詢:每月變化計算累積 - Postgres的SQL問題
select yr,
mn,
"%ind",
sum("%ind") OVER (order BY yr,mn) as "Sum%"
from table2
order by yr, mn;
結果是:
yr | mn | %ind | Sum%
------+----+--------------------+------------------
1996 | 2 | 18.1818181818182 | 18.1818181818182
1996 | 2 | 9.09090909090909 | 81.8181818181818
1996 | 2 | 9.09090909090909 | 90.9090909090909
1996 | 2 | 9.09090909090909 | 100
1996 | 3 | 12.1951219512195 | 112.19512195122
1996 | 3 | 31.0975609756098 | 143.292682926829
1996 | 3 | 0.609756097560976 | 199.390243902439
1996 | 3 | 0.609756097560976 | 200
1996 | 4 | 4.8780487804878 | 204.878048780488
1996 | 4 | 24.390243902439 | 268.29268292683
1996 | 4 | 14.6341463414634 | 298.780487804878
1996 | 4 | 1.21951219512195 | 300
這是一個問題,因爲什麼,我試圖做將%ind對應列的每一行添加給定的月份,例如1996-3。此外,一旦月份發生變化,我希望它重新開始從0增加到100%。因此,理想的表將是:
yr | mn | %ind | Sum%
------+----+--------------------+------------------
1996 | 2 | 18.1818181818182 | 18.1818181818182
1996 | 2 | 9.09090909090909 | 81.8181818181818
1996 | 2 | 9.09090909090909 | 90.9090909090909
1996 | 2 | 9.09090909090909 | 100
1996 | 3 | 12.1951219512195 | 12.19512195122
1996 | 3 | 14.0243902439024 | 86.585365853659
1996 | 3 | 0.609756097560976 | 99.390243902439
1996 | 3 | 0.609756097560976 | 100
1996 | 4 | 4.8780487804878 | 4.878048780488
1996 | 4 | 15.8536585365854 | 84.146341463415
1996 | 4 | 14.6341463414634 | 98.780487804878
1996 | 4 | 1.21951219512195 | 100
我的SQL查詢中缺少什麼?
這個查詢是給我100%都在列總和%的時間。你知道如何做到這一點從0增加到100%,然後在月份變化時重新啓動它嗎? –
@SamuelDonadelli:這是按照分區定義的相同值排序的結果。除非您有其他方式在一個月內定義訂單*,否則無法獲得正確的運行總額。在這裏看到:http://sqlfiddle.com/#!12/33838/1 –
@horse_with_no_name:很好的例子,我創造了這個ID序列,它能正常工作。謝謝。塞繆爾 –