SQL 测试表脚本
1 DECLARE @Temp Table 2 ( 3 ID INT, --- 月份 4 MoneyData Float --- 金额 5 ) 6 7 insert INTO @TEMP 8 SELECT 1,100 UNION ALL 9 SELECT 2,200 UNION ALL 10 SELECT 3,300 UNION ALL 11 SELECT 4,400 UNION ALL 12 SELECT 5,500 UNION ALL 13 SELECT 6,600 UNION ALL 14 SELECT 7,600
一 自连接
1 SELECT A.ID, SUM(B.MoneyData) FROM @Temp A INNER JOIN @Temp B 2 ON A.ID>=B.ID GROUP BY A.ID 3 ---- 重点在于 ON 条件,通过自连接 A.ID >= B.ID ,可获取所需数据,再通过GROUP BY 、SUM 即可统计求和
二 开窗函数
1 SELECT ID, MoneyData, SUM(MoneyData) OVER( ) AS ‘总销售额‘, 2 SUM(MoneyData) OVER( PARTITION BY ID ) AS ‘月销售额‘, 3 SUM(MoneyData) OVER( ORDER BY ID ASC) AS ‘当月+当月前销售额‘ 4 FROM @Temp 5 ---- 此处,使用开窗函数使用更为简单,不过,其中 SUM() OVER ( ORDER BY ID ASC ) 即可实现以上功能