27,579
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:[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
*/
--> 测试数据:[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
)
select MIN([时间]) as [时间]
from t
where t.累计使用数量>=(select [购买数量]
from [a表] a where t.道具id=a.道具id and t.用户=a.用户)
/*
时间
-----------
270
*/
if object_id('[a]') is not null drop table [a]
go
create table [a] (时间 int,用户 nvarchar(2),道具id nvarchar(2),购买数量 int,用完时间 nvarchar(2))
insert into [a]
select 123,'a','b',20,'X'
if object_id('[b]') is not null drop table [b]
go
create table [b] (时间 int,用户 nvarchar(2),道具id nvarchar(2),使用数量 int)
insert into [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
select * from [a]
select * from [b]
SELECT MIN(TB.时间)
FROM ( SELECT b.时间 ,
b.道具id ,
SUM(b2.使用数量) AS 使用数量
FROM b
INNER JOIN b b2 ON b.道具id = b2.道具id
AND b.时间 >= b2.时间
GROUP BY b.时间 ,
b.道具id
) tb
INNER JOIN a ON TB.道具id = a.道具id
AND a.购买数量 <= tb.使用数量
with t
as(
select
用户,道具id,sum(使用数量) as 使用数量
from b表
group by 用户,道具id
)'
m as
(
select a.* from a表 a,t
where a.用户=t.用户,
and a.道具id=t.道具id
a.购买数量<=t.使用数量
)
select * from m a
where a.时间=(select min(时间) from m b where a.道具id=b.道具id and a.购买数量<=b.使用数量 )