34,838
社区成员




----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-15 14:52:01
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([年] int,[月] int,[产品] varchar(1),[未出库数量] int)
insert [huang]
select 2013,11,'A',100 union all
select 2013,12,'A',150 union all
select 2014,1,'A',300 union all
select 2013,10,'B',1000 union all
select 2013,11,'B',1500 union all
select 2013,12,'B',3001
--------------开始查询--------------------------
;WITH cte AS (
select *,ROW_NUMBER()OVER(PARTITION BY [产品] ORDER BY [年],[月]) id
from [huang] )
SELECT [年],[月],[产品],ISNULL((SELECT SUM([未出库数量] ) FROM cte b WHERE a.id>b.id AND a.[产品]=b.[产品]),0)[未出库数量]
FROM cte a
ORDER BY [产品]
----------------结果----------------------------
/*
年 月 产品 未出库数量
----------- ----------- ---- -----------
2013 11 A 0
2013 12 A 100
2014 1 A 250
2013 10 B 0
2013 11 B 1000
2013 12 B 2500
*/
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-15 14:52:01
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([年] int,[月] int,[产品] varchar(1),[未出库数量] int)
insert [huang]
select 2013,11,'A',100 union all
select 2013,12,'A',150 union all
select 2014,1,'A',300 union all
select 2013,10,'B',1000 union all
select 2013,11,'B',1500 union all
select 2013,12,'B',3001
--------------开始查询--------------------------
;WITH cte AS (
select *,ROW_NUMBER()OVER(PARTITION BY [产品] ORDER BY [年],[月])id
from [huang] ),
cte1 AS (
SELECT *
FROM cte
WHERE id=1
UNION ALL
SELECT a.[年],a.[月],a.[产品],a.[未出库数量]+b.[未出库数量] AS [未出库数量],a.id
FROM cte a INNER JOIN cte1 b ON a.id-1=b.id AND a.[产品]=b.[产品]
)
SELECT [年],[月],[产品],[未出库数量]
FROM cte1
ORDER BY [产品]
----------------结果----------------------------
/*
年 月 产品 未出库数量
----------- ----------- ---- -----------
2013 11 A 100
2013 12 A 250
2014 1 A 550
2013 10 B 1000
2013 11 B 2500
2013 12 B 5501
*/