表里的数据为
a 1
b 2
c 3
d 4
想得到的数据为
a 1 1
b 2 3
c 3 6
d 4 10
即得到每一行与前面所有行的和
------解决思路----------------------
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-09-22 16:42:28
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([col1] varchar(1),[col2] int)
insert [huang]
select 'a',1 union all
select 'b',2 union all
select 'c',3 union all
select 'd',4
--------------开始查询--------------------------
select * ,sum(col2)OVER(ORDER BY col1)col3
from [huang]
----------------结果----------------------------
/*
col1 col2 col3
---- ----------- -----------
a 1 1
b 2 3
c 3 6
d 4 10
*/
------解决思路----------------------
啥版本。12以上直接用分析函数。
sum(列2) over(order by 列1) 直接用分析函数就OK 了
------解决思路----------------------
--不是这个12以上 就用这个吧
with cte as
(select 'a' as name,1 as qty union all
select 'b' as name,2 as qty union all
select 'c' as name,3 as qty union all
select 'd' as name,4 as qty ),
cte1 as
(select name,qty,ROW_NUMBER()over(order by name) as rn from cte)
select a.name,a.qty,sum(b.qty)as sums from cte1 as a join cte1 as b
on a.rn>=b.rn
group by a.name,a.qty
--结果
name qty sums
---- ----------- -----------
a 1 1
b 2 3
c 3 6
d 4 10