按日期累加销售数据

 原表:

表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 行受影响)

*/
大侠们,不愧为大侠啊!!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值