Monday, March 26, 2012

Query with index?

Hi,

I have a table, when I execute query I want to display an index of retrieved records.

Assume table has data like:

id name phone
3 Alan1 5487411
5 Alan2 5487412
9 Alan3 5487413
10 Alan4 5487414
11 Alan5 5487415
12 Alan6 5487416

Select * from table where phone > 5487412 AND phone < 5487415

So result must be like this

index id name phone
1 9 Alan3 5487413
2 10 Alan4 5487414

Who can I get this result by SQL query?

I am not sure I understand your question; are you looking for a row number for each row returned? Something like:

declare @.mockup table
( id tinyint primary key, -- Needs to be changed
[name] varchar(7), -- Needs to be changed
phone varchar(7) -- Needs to be changed
)

insert into @.mockup values (3, 'Alan1', '5487411')
insert into @.mockup values (5, 'Alan2', '5487412')
insert into @.mockup values (9, 'Alan3', '5487413')
insert into @.mockup values (10, 'Alan4', '5487414')
insert into @.mockup values (11, 'Alan5', '5487415')
insert into @.mockup values (12, 'Alan6', '5487416')

select row_number ()
over ( order by id )
as [index],
id,
[name],
phone
from @.mockup
where phone > 5487412
and phone < 5487415

-- index id name phone
-- - - - -
-- 1 9 Alan3 5487413
-- 2 10 Alan4 5487414

No comments:

Post a Comment