日期:2014-05-18 浏览次数:20518 次
with cte as ( select id,bonus,(select sum(bonus) from table_name where id <= t.id) as sum from table_name t ) select id from cte where sum < 1000
------解决方案--------------------
select ID from @t a where 1000>(select SUM(bonus) from @t where id<=a.id)
a 表@t 的别名
a.id 表别名中"字段ID",id<=a.id 意思是子查询中的ID要<= “select ID from @t a”这个查询中的ID当前值。
------解决方案--------------------
create table #try (id int identity(1,1), bonus int) insert #try select 89 union all select 97 union all select 83 union all select 94 union all select 83 union all select 97 union all select 99 union all select 81 union all select 84 union all select 92 union all select 98 union all select 91 union all select 82 union all select 83 union all select 95 union all select 98 union all select 81 declare @id as int declare @sum as int set @id=0 set @sum=0 select @id=(case when @sum+bonus<1000 then id else @id end), @sum=@sum+(case when @sum+bonus<1000 then bonus else 0 end) from #try order by id select id from #try where id<=11
------解决方案--------------------
--各位都是牛叉人物