案例:
原表有两列,分别为月份、月份销售额,而需要一条 SQL 语句实现统计出每个月份以及当前月以前月份销售额和
sql 测试数据准备:
DECLARE
@
Temp
Table
(
monthNo
INT
,
--- 月份
MoneyData
Float
--- 金额
)
insert
INTO
@
TEMP
SELECT
1,100
UNION
ALL
SELECT
2,200
UNION
ALL
SELECT
3,300
UNION
ALL
SELECT
4,400
UNION
ALL
SELECT
5,500
UNION
ALL
SELECT
6,600
UNION
ALL
SELECT
7,600
SELECT
monthNo, MoneyData, SUM
(MoneyData) OVER( )
AS
'总销售额'
,
SUM
(MoneyData) OVER( PARTITION
BY
ID )
AS
'当月销售额'
,
SUM
(MoneyData) OVER(
ORDER
BY
ID
ASC
)
AS
'截止当月累计销售额'
FROM
@
Temp
报错信息如下:
原因:SUM
(MoneyData) OVER (
ORDER
BY
ID
ASC
) 必须在sqlserver 2012版及以上执行
版本不满足的时候只能更换其他方式完成查询,如:
SELECT
A.monthNo, SUM
(B.MoneyData)
FROM
@
Temp
A
INNER
JOIN
@
Temp
B
ON
A.monthNo>=B.monthNo GROUP
BY
A.ID
------ 重点在于 ON 条件,通过自连接 A.monthNo >= B.monthNo ,可获取所需数据,再通过
GROUP
BY
、
SUM
即可统计求和