类型:转载 责任编辑:asp.net 日期:2007/05/23
热门软件下载:
有一个数据库A,字段如下:
lsh,流水号 主键
sl,数量
px,排序
如果选择,按px进行排序选则sum(sl)>280(指定数量)的记录.
如:有下面五条记录:
1、[lsh 1] [sl 100] [px 2]
2、[lsh 2] [sl 150] [px 3]
3、[lsh 3] [sl 200] [px 4]
4、[lsh 4] [sl 100] [px 5]
5、[lsh 5] [sl 80] [px 6]
记录选择出来是这样,这时要求sum(sl)>280时的出来,但后面[sl 200]这个要求被选中,
除非它刚好=250否则加[lsh 4]这条记录。
这时应该选出记录是[lsh 5]或者以后的这些记录,怎么实现最好?
网友回答:
关注,帮你顶!
--不知道是不是符合楼主的意思。
select top 2 *
from A
where px>( select top 1 px
from A t
where ( select sum(ls)
from A
where px<=t.px
)>=280
order by px
)
order by px
/* 創建測試環境
if not object_id(master..test) is null drop table test
create table test (lsh int IDENTITY (1,1) , sl int)
insert into test (sl)
select 100
union all
select 150
union all
select 200
union all
select 100
union all
select 80
*/
declare @lsh as int,@sl as int
declare @sl_sum as int
set @sl_sum = 0
declare test_cursor cursor forward_only for
select * from test order by lsh
open test_cursor
fetch next from test_cursor INTO @lsh , @sl
while @@FETCH_STATUS=0
begin
set @sl_sum = @sl_sum + @sl
if @sl_sum >=280 break
fetch next from test_cursor INTO @lsh , @sl
end
close test_cursor
deallocate test_cursor
select * from test where lsh>@lsh
--drop table test
/*測試 結果
lsh sl
----------- -----------
4 100
5 80
(2 row(s) affected)
*/
在存储过程中实现最好,创建临时表来处理,这样就很少有循环,时间会快很多。
上面以lsh排序只是一個例子,你可以將它改成那個(或兩個)用於排序的字段呀.