日期:2014-05-16  浏览次数:20506 次

累加求和的sql 语句
一个简单实用的问题,表结构如下,两列,月份和销量。想增加一列,显示累计销量,希望能用一句sql语言实现。谢谢

month  sales
1              10
2               20 
3               30

month  sales    accu. sales
1              10             10
2               20             30 
3               30             60
------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_HuangZJ(发粪涂墙)
-- Date    :2014-04-10 20:14:52
-- Version:
--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) 
-- Apr  2 2010 15:48:46 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([month] int,[sales] int)
insert [huang]
select 1,10 union all
select 2,20 union all
select 3,30
--------------生成数据--------------------------

select * ,(SELECT SUM([sales]) FROM huang a WHERE a.[month]<=huang.[month])[accu. sales]
from [huang]
----------------结果----------------------------
/* 
month       sales       accu. sales
----------- ----------- -----------
1           10          10
2           20          30
3           30          60
*/