日期:2014-05-18  浏览次数:20517 次

统计数据问题求教
有两个表 一个购买表,一个使用表,字段如下
a表 时间 用户 道具id 购买数量 用完时间

b表 时间 用户 道具id 使用数量 

现在a表某个道具买了M个,b表记录了这个道具每次使用量n,求这个道具累计使用量sum(n)>=M的最小时间

------解决方案--------------------
SQL code

--> 测试数据:[a表]
if object_id('[a表]') is not null 
drop table [a表]
create table [a表](
[时间] int,
[用户] varchar(1),
[道具id] varchar(1),
[购买数量] int,
[用完时间] varchar(1)
)
insert [a表]
select 123,'a','b',20,'X'
--> 测试数据:[b表]
if object_id('[b表]') is not null 
drop table [b表]
create table [b表](
[时间] int,
[用户] varchar(1),
[道具id] varchar(1),
[使用数量] int
)
insert [b表]
select 235,'a','b',5 union all
select 250,'a','b',10 union all
select 270,'a','b',6 union all
select 285,'a','b',7

with t
as(
select *,
(select SUM([使用数量]) from [b表] b where a.时间>=b.时间) as [累计使用数量]
from [b表] a where a.时间>=(select [时间] from [a表] b 
where a.道具id=b.道具id and a.用户=b.用户)
)
select MIN([时间]) as [时间]
from t 
where t.累计使用数量>=(select [购买数量] 
from [a表] a where t.道具id=a.道具id and t.用户=a.用户)
/*
时间
-----------
270
*/