views:

48

answers:

2

Using SQL Server 2008, but could relate to other databases as well probably.

If I had the following data (table t):

id text  date
1 Data1 2/1/2009
2 Data2 2/2/2009
3 Data3 2/3/2009
4 Data4 2/4/2009
5 Data5 2/5/2009

How could I find the index of a certain record?

indexOf(select id from t where id = 1) = 0

or

indexOf(select id from t where date = '2/4/2009') = 3

I think it has something to do with ROW_Number() but not really sure...

+1  A: 

Edit
select * from (select ROW_NUMBER() over ( order by id) -1 as Index,* from table) a where --condition

ps
+2  A: 

Yes, ROW_NUMBER is exactly what you want to leverage along with the OVER clause. You can accomplish what you are trying to do using a sub-query or a CTE such as this:

;WITH Q as (
    SELECT id, text, date, ROW_NUMBER() OVER (ORDER BY date) as RowNumber 
    FROM t
)
SELECT * FROM Q WHERE RowNumber = 3
Justin Swartsel
Looks easy enough, I'll give it a whirl.
rball
I think I just don't need the WITH Q parts, but this did the trick. PS was also correct, but left out the "RowNumber" which I guess I'll rename to "Index". But sort of a shared answer... :)
rball
Yep ps did the same w/ sub-query... i just gravitate to CTE's more these days for some reason. More readable to me :)
Justin Swartsel
if you ask me, i will also recommend the CTE.
ps
makes sense, thanks
rball