数据库
首页 > 数据库> > 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

查询结果如下:

 

标签:INSERT,SUMOVER,函数,酱油,INTO,VALUES,开窗,sum,牛奶
来源: https://www.cnblogs.com/SQLPLUS/p/14850588.html