首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

统计数据有关问题求教

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

统计数据问题求教
有两个表 一个购买表,一个使用表,字段如下
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 allselect 250,'a','b',10 union allselect 270,'a','b',6 union allselect 285,'a','b',7with tas(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*/ 

热点排行