原表:
表1
日期 店铺 销售 9-1 A店 100 9-1 B店 200 9-1 C店 300 9-2 A店 200 9-2 B店 300 9-2 C店 400 9-3 A店 300 9-3 B店 400 9-3 C店 500 ---期望结果如下: 日期 店铺 销售 累计销售 9-1 A店 100 100 9-1 B店 200 200 9-1 C店 300 300 9-2 A店 200 300 --300为9-1和9-2的销售总和 9-2 B店 300 500 9-2 C店 400 700 9-3 A店 300 600 9-3 B店 400 900 9-3 C店 500 1200 |
解决方法:
一:(引自:子陌红尘[I'm 潇湘])
select
a.日期,a.店铺,sum(b.销售) as 销售
from
表1 a,表1 b
where
a.店铺=b.店铺
and
a.日期>=b.日期
group by
a.日期,a.店铺
order by
a.日期,a.店铺
二:(引自小F )
----------------------------------------------------------------
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2009-10-30 16:23:42
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([日期] varchar(3),[店铺] varchar(3),[销售] int)
insert [tb]
select '9-1','A店',100 union all
select '9-1','B店',200 union all
select '9-1','C店',300 union all
select '9-2','A店',200 union all
select '9-2','B店',300 union all
select '9-2','C店',400 union all
select '9-3','A店',300 union all
select '9-3','B店',400 union all
select '9-3','C店',500
--------------开始查询--------------------------
select
*,
(select sum(销售) from tb where 日期<=t.日期 and 店铺=t.店铺) as 累计销售
from
tb t
----------------结果----------------------------
/* 日期 店铺 销售 累计销售
---- ---- ----------- -----------
9-1 A店 100 100
9-1 B店 200 200
9-1 C店 300 300
9-2 A店 200 300
9-2 B店 300 500
9-2 C店 400 700
9-3 A店 300 600
9-3 B店 400 900
9-3 C店 500 1200
(9 行受影响)
*/
大侠们,不愧为大侠啊!!!!!