Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

tsql - Row_Number simulation in Sql server 2000

I have a sample input table as

Declare  @input TABLE(Name VARCHAR(8))
INSERT INTO @input(Name)  values('Aryan') 
INSERT INTO @input(Name)  values('Aryan') 
INSERT INTO @input(Name)  values('Joseph') 
INSERT INTO @input(Name)  values('Vicky') 
INSERT INTO @input(Name)  values('Jaesmin') 
INSERT INTO @input(Name)  values('Aryan') 
INSERT INTO @input(Name)  values('Jaesmin') 
INSERT INTO @input(Name)  values('Vicky') 
INSERT INTO @input(Name)  values('Padukon') 
INSERT INTO @input(Name)  values('Aryan') 
INSERT INTO @input(Name)  values('Jaesmin') 
INSERT INTO @input(Name)  values('Vick') 
INSERT INTO @input(Name)  values('Padukon') 
INSERT INTO @input(Name)  values('Joseph') 
INSERT INTO @input(Name)  values('Marya') 
INSERT INTO @input(Name)  values('Vicky')

Also I have a tally table as under

declare @t table(n int)
insert into @t select 1 union all select 2 union all
select 3 union all select 4 union all select 5 union all
select 6 union all select 7 union all select 8 union all
select 9 union all select 10 union all select 11 union all
select 12 union all select 13 union all select 14 union all
select 15 union all select 16 union all select 17 union all
select 18 union all select 19 union all select 20

In Sql Server 2005 if I do as

 Select rn, name from (
    select ROW_NUMBER()over (order by Name) as rn , * from @input) x
    where rn % 2 <> 0

I get the output as

rn  name
1   Aryan
3   Aryan
5   Jaesmin
7   Jaesmin
9   Joseph
11  Padukon
13  Vick
15  Vicky

Bu I am restricted to Sql server 2000. How can I get the same output?

I have tried with

SELECT name, (SELECT COUNT(*) FROM @input AS i2 WHERE i2.Name <= i1.Name) As rn
FROM @input AS i1

but the output is wrong

name    rn
Aryan   4
Aryan   4
Joseph  9
Vicky   16
Jaesmin 7
Aryan   4
Jaesmin 7
Vicky   16
Padukon 12
Aryan   4
Jaesmin 7
Vick    13
Padukon 12
Joseph  9
Marya   10
Vicky   16
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Declare your table variable as

Declare  @input TABLE(_id int identity(1, 1), Name VARCHAR(8))

And then reqrite your query as

Select _id, name 
from @input
where _id % 2 <> 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...