日期:2014-05-17  浏览次数:20589 次

一个数据统计问题
 商品买卖的统计问题
基础表记录 每次进货和出货的信息,主要包括 日期 商品名称 买卖标识 数量 单价 额外费用,这个额外费用,是算在成本里面的,比如:买的时候运费,卖的时候租金(房租摊下来)具体不用管,算到成本里面就可以。
需要统计:
1、每次进货的收益(单个商品):(出货数量×单价-额外费用)-(进货数量*单价+额外费用)
2、每个月收益按商品:相当于对没次进货收益 按商品名称和日期group一下
但问题是 一次进货的商品 可能分多次才能卖完。
ID 日期  标识   商品  单价 数量 额外费用(标识 1进货 0出货)
1 2012-10-05  1 牙膏 3.5 200 20
2 2012-10-06  0 牙膏 6   50 5  
3 2012-10-07  0 牙膏 5   130 10
4 2012-10-08  1 牙膏 3.8   120 15
5 2012-10-09  0 牙膏 6   80 6
9 2012-10-10  0 牙膏 6   60 5
同样的商品,因为进货或者出货的数量不一样,价格也可能不一样的。
上面这几条记录:
 日期  商品名称   亏盈(亏是负数)
2012-10-05  牙膏 (6*20-6/2(不是同一次进货,额外费用平摊))+(5*130-10)+(6*50-5)-(3.5*200+20)=332
2012-10-08  牙膏  (60*6-6/2)+(60*6-5)-(3.8*120+15)=241

因为每次出货的商品,可能不是同一次进的货。稍微有些麻烦,为了统计方便,也可以添加一个中间表,麻烦各位大侠,帮看一下。

 
------最佳解决方案--------------------
---------------------------------
--  Author: HEROWANG(让你望见影子的墙)
--  Date  : 2012-11-05 13:22:44
--  blog  : blog.csdn.net/herowang
---------------------------------
 
IF OBJECT_ID('[tb]') IS NOT NULL 
    DROP TABLE [tb]
go
CREATE TABLE [tb] (ID INT,日期 DATETIME,标识 INT,商品 VARCHAR(4),单价 NUMERIC(2,1),数量 INT,额外费用 INT)
INSERT INTO [tb]
SELECT 1,'2012-10-05',1,'牙膏',3.5,200,20 UNION ALL
SELECT 2,'2012-10-06',0,'牙膏',6,50,5 UNION ALL
SELECT 3,'2012-10-07',0,'牙膏',5,130,10 UNION ALL
SELECT 4,'2012-10-08',1,'牙膏',3.8,120,15 UNION ALL
SELECT 5,'2012-10-09',0,'牙膏',6,80,6 UNION ALL
SELECT 9,'2012-10-10',0,'牙膏',6,60,5
--select * from [tb]
;
with
wang as(
select *,zj=case 标识 when 1 then -(单价*数量+额外费用) else 单价*数量-额外费用 end,sl=case 标识 when 1 then 数量 else -数量 end
from tb),
wang1 as
(
select 日期,商品,sl=case when exists(select 1 from wang where 商品=t.商品 and 日期>t.日期 and 标识=1) 
      then (select sum(sl) from wang where 商品=t.商品 and 日期>=t.日期 and 日期<(select top 1 日期 from wang where 日期>t.日期 and 标识=1 order by 日期))
      else (select sum(sl) from wang where 商品=t.商品 and 日期>=t.日期) end
,单价=case when exists(select 1 from wang where 商品=t.商品 and 日期>t.日期 and 标识=1) 
      then (select top 1 单价 from wang where 日期>(select top 1 日期 from wang where 日期>t.日期 and 标识=1 order by 日期))
      else (select top 1 单价 from wang where 商品=t.商品 and 日期>t.日期) end
,额外费用=case when exists(select 1 from wang where 商品=t.商品 and 日期>t.日期 and 标识=1) 
      then (select count(*) from wang where 日期>(select top 1 日期 from wang where 日期>t.日期