在表格中,我有字段pwd,如001,002,003,004。
为了获得最高价值,我会这样做
("SELECT pwd FROM users WHERE pwd= (SELECT max(pwd) FROM users)")
这样我得到了数字004.要增加它并再次添加到表格我使用
biggest= CInt((SQLDataset.Tables(0).Rows(0).Item(0)))
Dim test As String = "000" & biggest
txtpwd.Text = test.Substring(test.Length - 3)
test2 = test.Substring(test.Length - 3)
但是,如果我想找到第一个可用数字(缺少一个),该怎么办?例如,如果我有
001, 002, 003 ,005 , 006 , 007 , 009 , 013.
我想抓住号码004
。我怎么能这样做。
答案 0 :(得分:2)
您可以使用子查询(假设sql-server):
SELECT MIN(u.pwd) + 1 AS FirstMissing
FROM users u
WHERE (u.pwd + 1) <> (SELECT TOP 1 u2.pwd
FROM users u2
WHERE u2.pwd > u.pwd)
如果你想在内存中这样做,因为你已经拥有DataSet
,你可以使用以下Linq-To-DataSet查询。但我强烈建议不要在客户端进行过滤。
Dim rows = SQLDataset.Tables(0).AsEnumerable()
Dim missing = From row In rows
Let id = row.Field(Of Int32)(0)
Let nextId = rows.Select(Function(r) r.Field(Of Int32)(0)).
Where(Function(idNext) idNext > id).
OrderBy(Function(idNext) idNext).
DefaultIfEmpty(-1).
First()
Where nextId <> -1 AndAlso id + 1 <> nextId
Select id + 1
Dim firstMissing As Int32 = missing.FirstOrDefault()
如果string
实际上是DataTable
,您可以使用Int32.Parse
:
Dim missing = From row In rows
Let id = Int32.Parse(row.Field(Of String)(0))
Let nextId = rows.Select(Function(r) Int32.Parse(r.Field(Of String)(0))).
Where(Function(idNext) idNext > id).
OrderBy(Function(idNext) idNext).
DefaultIfEmpty(-1).
First()
Where nextId <> -1 AndAlso id + 1 <> nextId
Select id + 1
答案 1 :(得分:1)
您需要为空表提供案例。
declare @data table (Value char(3))
select ISNULL(RIGHT('00' + CONVERT(varchar(10), MIN(Number)), 3), '001') AS FirstMissingValue
from
(
-- Inner Table
select Value, ROW_NUMBER() OVER (ORDER BY Value) Number
from @data
) data
where Value <> Number
insert @data values('001'), ('002'), ('003') ,('008'), ('006')
select ISNULL(RIGHT('00' + CONVERT(varchar(10), MIN(Number)), 3), '001') AS FirstMissingValue
from
(
-- Inner Table
select Value, ROW_NUMBER() OVER (ORDER BY Value) Number
from @data
) data
where Value <> Number
结果
FirstMissingValue
-----------------
001
FirstMissingValue
-----------------
004
答案 2 :(得分:1)
这样我将获得数组中所有缺失的数字,然后我使用行索引0来获得第一个。
select u1.pwd+1 as firstmissing
from users as u1
left outer join users as u2
on u2.pwd=u1.pwd+1
where u2.pwd is null