能否有这样的查询?
充值记录表
id------Money-------D_T
1 ----- 200.00 ------2013-05-04 12:22:24
2 ----- 300.00 ------2013-05-04 12:22:26
3 ----- 500.00 ------2013-05-04 12:22:54
4 ----- 200.00 ------2013-05-04 12:23:24
查询最后充值总额达到1000元的所有记录。
需求分析:某会员帐户里有1000元,我想查他这1000元是怎么充进来的。
从肉眼判断,我们知道,这1000元的充值分别是id=2, 3, 4的记录充进来的。
但能用sql查出来吗?
谢谢!万分感谢。
[解决办法]
create table #tb(id int,[Money] numeric(12,2),D_T datetime)
insert into #tb
select 1,200.00,'2013-05-04 12:22:24'
union all select 2,300.00,'2013-05-04 12:22:26'
union all select 3,500.00,'2013-05-04 12:22:54'
union all select 4,200.00,'2013-05-04 12:23:24'
select * from #tb
select *
from (
select *,(select sum([money]) from #tb b where b.id<=a.id) as l_money
from #tb a
)t
where l_money>=1000
/*
3500.002013-05-04 12:22:54.0001000.00
4200.002013-05-04 12:23:24.0001200.00
*/
if OBJECT_ID('tempdb..#temp', 'u') is not null drop table #temp;
go
create table #temp(会员ID INT, [id] INT, [Money] DECIMAL(10,2), [D_T] DATETIME);
insert #temp
select '1','1','200.00','20130504 12:22:24' union all
select '1','2','300.00','20130504 12:22:26' union all
select '1','3','500.00','20130504 12:22:54' union all
select '1','4','200.00','20130504 12:23:24'
--方法2:
SELECT t.会员ID, t.id, t.[Money], t.[D_t] FROM
(
SELECT *,
总充值金额=SUM(m.[Money]) OVER(PARTITION BY 会员ID),
累计充值金额=(SELECT SUM([Money]) FROM #temp n WHERE n.会员ID=m.会员ID AND n.d_t >= m.d_t)
FROM #temp m
) t
WHERE 总充值金额 >= 1000
AND 累计充值金额 <= 1000
/*
会员IDidMoneyD_t
12300.002013-05-04 12:22:26.000
13500.002013-05-04 12:22:54.000
14200.002013-05-04 12:23:24.000
*/