请教一个SQL语句

artwl_cn 2010-09-26 03:59:25
数据如图:


想要实现的功能,传进一个数字,从如图表中随机选出一个FillCount的和大于或等于这个数字的ID的集合(当然,选出的ID的个数应该不大于传进的数字,因为FillCount至少为1)

例如:
传进的数字是5,则选出的ID可能是38、40 或 41、42 或38、42.....等

但绝不会是38、39、40 或 38、40、41(因为前两个FillCount的和已经是5或大于5了,所以没必要选第三个)


不知道描述清楚没,请教大家了!
...全文
206 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
artwl_cn 2010-09-26
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 sqlcenter 的回复:]
SQL code
declare @t table(id int)

declare @num int, @id int, @fc int
set @num = 5

while @num>0
begin
select top 1 @id=ID, @fc=FillCount from tbname where FillCount<=@num and ID not in (s……
[/Quote]
非常感谢!
SQLCenter 2010-09-26
  • 打赏
  • 举报
回复
declare @t table(id int)

declare @num int, @id int, @fc int
set @num = 5

while @num>0
begin
select top 1 @id=ID, @fc=FillCount from tbname where FillCount<=@num and ID not in (select id from @t) order by newid()
insert @t select @id
set @num = @num - @fc
end

select * from @t
SQLCenter 2010-09-26
  • 打赏
  • 举报
回复
declare @t table(id int)

declare @num int, @id int, @fc int
set @num = 5

while @num>0
begin
select top 1 @id=ID, @fc=FillCount from tbname where colid<=@num and ID not in (select id from @t) order by newid()
insert @t select @id
set @num = @num - @fc
end

select * from @t
liaoyukun111 2010-09-26
  • 打赏
  • 举报
回复
有 点遍历的意思 游标吗
zhangsuyunpk521 2010-09-26
  • 打赏
  • 举报
回复
路过,帮顶!~~~
whb147 2010-09-26
  • 打赏
  • 举报
回复
贪心?
加权路径?
BaoShiqiang 2010-09-26
  • 打赏
  • 举报
回复
这个不会 等大牛 召唤 树哥 水哥 东升哥 土豆哥
-小蕾- 2010-09-26
  • 打赏
  • 举报
回复
貌似这个用sql有点难度。
为啥不用代码判断?
「已注销」 2010-09-26
  • 打赏
  • 举报
回复
rimtd0314 2010-09-26
  • 打赏
  • 举报
回复
帮顶``````
artwl_cn 2010-09-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 dawugui 的回复:]
看是看懂了,不过用SQL来做,太勉为其难了,帮顶。
[/Quote]
这个用存储过程不好吗?
dawugui 2010-09-26
  • 打赏
  • 举报
回复
看是看懂了,不过用SQL来做,太勉为其难了,帮顶。

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧