Java教程

sql开窗函数_累计求和开窗函数sum()over()

本文主要是介绍sql开窗函数_累计求和开窗函数sum()over(),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

需求:有如下示例数据,其中PRODUCT表示产品,CONTRACT_MOUTH表示合同月份,AMOUNT表示当月合同金额,请求出每个产品累计合同金额。

比如牛奶2月份累计求和金额为100+200=300,牛奶3月份累计求和金额为100+200+300=600,依此类推。

示例数据sql:

CREATE TABLE SUMOVER(
PRODUCT VARCHAR(50),
CONTRACT_MOUTH INT,
AMOUNT DECIMAL(18,2)
)

INSERT INTO SUMOVER VALUES ('牛奶','1','100')
INSERT INTO SUMOVER VALUES ('牛奶','2','200')
INSERT INTO SUMOVER VALUES ('牛奶','3','300')
INSERT INTO SUMOVER VALUES ('牛奶','4','400')
INSERT INTO SUMOVER VALUES ('牛奶','5','500')
INSERT INTO SUMOVER VALUES ('牛奶','6','600')
INSERT INTO SUMOVER VALUES ('牛奶','7','700')
INSERT INTO SUMOVER VALUES ('牛奶','8','800')
INSERT INTO SUMOVER VALUES ('牛奶','9','900')
INSERT INTO SUMOVER VALUES ('牛奶','10','1000')
INSERT INTO SUMOVER VALUES ('牛奶','11','1100')
INSERT INTO SUMOVER VALUES ('牛奶','12','1200')
INSERT INTO SUMOVER VALUES ('酱油','1','100')
INSERT INTO SUMOVER VALUES ('酱油','2','200')
INSERT INTO SUMOVER VALUES ('酱油','3','300')
INSERT INTO SUMOVER VALUES ('酱油','4','400')
INSERT INTO SUMOVER VALUES ('酱油','5','500')
INSERT INTO SUMOVER VALUES ('酱油','6','600')
INSERT INTO SUMOVER VALUES ('酱油','7','700')
INSERT INTO SUMOVER VALUES ('酱油','8','800')
INSERT INTO SUMOVER VALUES ('酱油','9','900')
INSERT INTO SUMOVER VALUES ('酱油','10','1000')
INSERT INTO SUMOVER VALUES ('酱油','11','1100')
INSERT INTO SUMOVER VALUES ('酱油','12','1200')
View Code

查询sql如下:

SELECT  
    *,
    SUM(AMOUNT)OVER(PARTITION BY PRODUCT ORDER BY CONTRACT_MOUTH) AS SUM_AMOUNT
FROM SUMOVER

查询结果如下:

 

这篇关于sql开窗函数_累计求和开窗函数sum()over()的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!