34,838
社区成员




declare @t table
(
id int identity(1,1),
原单号 char(5),
新单号 char(5)
)
insert @t select '00010','00010'
union all select '00010','00020'
union all select '00020','00021'
union all select '00011','00011'
union all select '00011','00021'
union all select '00021','00022'
union all select '0010','0010'
union all select '0010','0020'
union all select '0020','0030'
select
a.原单号,
a.新单号,
最早单号 = (
select top 1 新单号
from @t
where 原单号 = 新单号
and id <= a.id
order by 新单号 desc)
from @t a
-- Test Data: ta
IF OBJECT_ID('ta') IS NOT NULL
DROP TABLE ta
Go
CREATE TABLE ta(原单号 NVARCHAR(8),新单号 NVARCHAR(8))
Go
insert ta select '00010','00010'
union all select '00010','00020'
union all select '00020','00021'
union all select '00011','00011'
union all select '00011','00021'
union all select '00021','00022'
union all select '0010','0010'
union all select '0010','0020'
union all select '0020','0030'
GO
--Start
;with t
as(
SELECT 原单号 ,新单号 ,原单号 as 最早单号 FROM ta where 原单号 = 新单号
union all
select ta.原单号 ,ta.新单号 ,t.原单号 as n from t ,ta where t.新单号 = ta.原单号 and t.新单号 < ta.新单号)
select * from t
order by 1,2
/*
(9 行受影响)
原单号 新单号 最早单号
-------- -------- --------
00010 00010 00010
00010 00020 00010
00011 00011 00011
00011 00021 00011
00020 00021 00010
00021 00022 00020
00021 00022 00011
0010 0010 0010
0010 0020 0010
0020 0030 0010
(10 行受影响)
*/
------------------------------------
-- Author: happyflsytone
-- Date:2008-10-25 23:48:07
------------------------------------
-- Test Data: ta
IF OBJECT_ID('ta') IS NOT NULL
DROP TABLE ta
Go
CREATE TABLE ta(原单号 NVARCHAR(4),新单号 NVARCHAR(4))
Go
INSERT INTO ta
SELECT '0001','0001' UNION ALL
SELECT '0001','0002' UNION ALL
SELECT '0002','0003' UNION ALL
SELECT '0010','0010' UNION ALL
SELECT '0010','0020' UNION ALL
SELECT '0020','0030'
GO
--Start
;with t
as(
SELECT 原单号 ,新单号 ,原单号 as 最早单号 FROM ta where 原单号 = 新单号
union all
select ta.原单号 ,ta.新单号 ,t.原单号 as n from t ,ta where t.新单号 = ta.原单号 and t.新单号 < ta.新单号)
select * from t
order by 1,2
--Result:
/*
原单号 新单号 最早单号
---- ---- ----
0001 0001 0001
0001 0002 0001
0002 0003 0001
0010 0010 0010
0010 0020 0010
0020 0030 0010
(6 行受影响)
*/
--End
declare @t table
(
原单号 char(4),
新单号 char(4)
)
insert @t select '0001','0001'
union all select '0001','0002'
union all select '0002','0003'
union all select '0010','0010'
union all select '0010','0020'
union all select '0020','0030'
select
a.原单号,
a.新单号,
最早单号 = (
select top 1 原单号
from @t
where 原单号 = 新单号
and 新单号 <= a.新单号
order by 新单号 desc)
from @t a
/**
0001 0001 0001
0001 0002 0001
0002 0003 0001
0010 0010 0010
0010 0020 0010
0020 0030 0010
**/