求一sql語句

TTLOVEYOU3344 2004-12-30 11:09:36
假如有個表 a,ID VARCHAR(9)
id
GMN000001
GMN000002
GMN000003
GMN000004
GMN000005
GMN000006
GMN000008
ABS000008
我要找的就是把中間的斷碼找出來,上面的數據,應該要顯示GMN000007,注意ID都是GMN開頭(其他字符開頭的不能出現在結果集裡)的,
怎麼才能把所有的中間缺碼的找出來?
...全文
93 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
vinsonshen 2004-12-30
  • 打赏
  • 举报
回复
select 'GMN'+right(1000000+a.id+1,6) from
(select cast(right(id,len(id)-len('GMN')) as int) as id from t_test where left(id,3)='GMN') as a
left join
(select min(cast(right(id,len(id)-len('GMN')) as int)) as id from t_test where left(id,3)='GMN'
union all
select max(cast(right(id,len(id)-len('GMN')) as int)) from t_test where left(id,3)='GMN') as b
on a.id=b.id
where b.id is null and not exists (select * from t_test where left(id,3)='GMN' and right(id,len(id)-len('GMN'))=a.id+1)
子陌红尘 2004-12-30
  • 打赏
  • 举报
回复
需要借助临时表,一旦出现连续的断码,楼上的方法就不能用了。
TTLOVEYOU3344 2004-12-30
  • 打赏
  • 举报
回复
問題解決,謝謝 iswear428跟hdhai9451,馬上結貼!
Andy__Huang 2004-12-30
  • 打赏
  • 举报
回复

create table tb(id varchar(20))
Insert into tb
select 'GMN000001'
union all select 'GMN000002'
union all select 'GMN000003'
union all select 'GMN000004'
union all select 'GMN000005'
union all select 'GMN000006'
union all select 'GMN000008'
union all select 'ABS000008'

select * from
(select ID=left(id,3)+replicate('0',6-len(cast(right(id,6) as numeric)+1))+cast(cast(right(id,6) as numeric)+1 as varchar) from tb where left(id,3)='GMN')a
where not exists(select id from tb where id=a.id) and id<=(select max(id) from tb where left(id,3)='GMN')

--結果:
id
GMN000007
mediafang2003 2004-12-30
  • 打赏
  • 举报
回复
关注!
iswear428 2004-12-30
  • 打赏
  • 举报
回复
--构建一个临时表,存储自动编号
declare @max int
declare @min int

select max(substring(id,3,len(id)-1)) into @max,min(substring(id,3,len(id)-1)) into @min
from table1

declare @temp table(id varchar(20) )
while @max>=@min
begin
insert into @temp values('GMN'+left('000000'+convert(varchar(6),@max),6))
set @max =@max-1
end

--获得被删除的ID
select id
from @temp
where id not in(select id from table1)
NinGoo 2004-12-30
  • 打赏
  • 举报
回复
TTLOVEYOU3344 2004-12-30
  • 打赏
  • 举报
回复
由於這個表的資料比較大,希望老大給我一個好的算法,如果有不清楚的地方,tt_liu1118@hotmail.com我在線等,比較急,老大們多多幫忙啊!

34,872

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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