我有一个类似数据的表。选择一个范围内的最小数量
ItemCode
1000
1002
1003
1020
1060
我想写一个SQL语句来获得的最低数量(ItemCode)未在该表中,它应该是能够得到一个最低数,一旦前面的最小订单ID已经被插入在表中,但也跳过已经在数据库中的数字。每次查询运行时我只想得到1个结果。
因此,它应该得到1001
作为基于上表的第一个结果。一旦ItemCode = 1001
已被插入到表格中,应该得到的下一个结果应该是1004
,因为1000
到1003
已经存在于表格中。
基于我在网上看到的一切,我认为,我必须使用While循环来做到这一点。这是我还在研究的代码。
DECLARE @Count int
SET @Count= 0
WHILE Exists (Select ItemCode
from OITM
where itemCode like '10%'
AND convert(int,ItemCode) >= '1000'
and convert(int,ItemCode) <= '1060')
Begin
SET @COUNT = @COUNT + 1
select MIN(ItemCode) + @Count
from OITM
where itemCode like '10%'
AND convert(int,ItemCode) >= '1000'
and convert(int,ItemCode) <= '1060'
END
我觉得有一个更简单的方法来实现这一点。有没有办法让我说......
选择未在表中存在1000和1060之间的最小数量的X
编辑:创建一个新的表不是一个选项,我案例
最后编辑:谢谢你们!我知道了。这是我最后的查询,返回我想要的。我知道我没有理由让它变得太复杂了!
With T0 as (select convert(int,ItemCode) + row_number() over (order by convert(int,ItemCode)) as ItemCode
from OITM
where itemCode like '10%'
AND convert(int,ItemCode) >= '1000'
And convert(int,ItemCode) <= '1060')
Select MIN(convert(varchar,ItemCode)) as ItemCode
from T0
where convert(int,ItemCode) Not in (Select convert(int,ItemCode)
from OITM
where itemCode like '10%'
AND convert(int,ItemCode) >= '1000'
and convert(int,ItemCode) <= '1060');
您不需要创建表,您可以根据wewesthemenace提供的解决方案使用'CTE'或'sys.columns' – ughai