PostgreSQL完成按月累加

PostgreSQL完成按月累加

背景

統計某個指標,指標按照月進行累加,注意需要按省份和年份進行分組。
在這裏插入圖片描述

方法一、使用自關聯

-- with 按月統計得到中間結果
WITH yms AS (SELECT regionid,SUM(getnum) AS getnum,SUM(dealnum) AS dealnum,to_char(qndate,'yyyy-MM') AS yearmonth
FROM t_queuenumber
GROUP BY regionid,to_char(qndate,'yyyy-MM')
ORDER BY regionid,yearmonth)

-- 查用子查詢解決。
SELECT s1.regionid,s1.yearmonth, getnum,dealnum,
(SELECT SUM(getnum) FROM yms  s2 WHERE s2.regionid = s1.regionid AND s2.yearmonth <= s1.yearmonth  AND SUBSTRING(s1.yearmonth,0,5) = SUBSTRING(s2.yearmonth,0,5) ) AS getaccumulatednum,
(SELECT SUM(dealnum) FROM yms  s2 WHERE s2.regionid = s1.regionid AND s2.yearmonth <= s1.yearmonth  AND  SUBSTRING(s1.yearmonth,0,5) = SUBSTRING(s2.yearmonth,0,5) ) AS accumulatednum
FROM yms s1;

查詢的結果如下:
在這裏插入圖片描述

方法二、使用窗口函數

更多關於窗口函數的用法,可以參考以前的文章。窗口函數十分適合這樣的場景:

	WITH yms AS (SELECT regionid,SUM(getnum) AS getnum,SUM(dealnum) AS dealnum,to_char(qndate,'yyyy-MM') AS yearmonth
	FROM t_queuenumber
	GROUP BY regionid,to_char(qndate,'yyyy-MM')
	ORDER BY regionid,yearmonth)
	-- 窗口函數的使用
	SELECT regionid,yearmonth,
	SUM(getnum) OVER(PARTITION BY regionid,SUBSTRING(yearmonth,0,5) ORDER BY yearmonth) AS getaccumulatednum,
	SUM(dealnum) OVER(PARTITION BY regionid ,SUBSTRING(yearmonth,0,5) ORDER BY yearmonth)  AS dealaccumulatednum
	FROM yms; 

在這裏插入圖片描述


後記

可以使用子查詢、可以使用窗口函數完成上面業務場景。

發佈了274 篇原創文章 · 獲贊 119 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章