Question

I'm working with the SQL Server database. Say, I have a selection that returns an array of IDs. Can I find out (with SQL) the order of an ID equalled N in that array?

Here's what I mean. This is my actual selection:

SELECT [id] FROM [dbo.test_db_002] t1
LEFT JOIN [dbo.test_db_003] t2 
ON t1.[id]=t2.[itmid] 
ORDER BY t2.[iid] ASC;

Say, it will return the following array of IDs:

13, 7, 34, 5, 2, 14

And, say I need to know what index is ID=5 in that array (the answer is 3, if 13 is index 0, 7 = index 1, 34 = index 2, 5 = becomes index 3.)

Was it helpful?

Solution

Try using ROW_NUMBER():

SELECT ROW_NUMBER() OVER (ORDER BY t2.[iid] ASC) -1 AS RowIndex
    ,[id] 
FROM [dbo.test_db_002] t1
LEFT JOIN [dbo.test_db_003] t2 
    ON t1.[id]=t2.[itmid] 
ORDER BY t2.[iid] ASC;

More on it here http://msdn.microsoft.com/en-us/library/ms186734.aspx

OTHER TIPS

Try this:

SELECT x.RowNum - 1
FROM
(
    SELECT [id], ROW_NUMBER() OVER (ORDER BY t2.[iid]) as RowNum 
    FROM   [dbo.test_db_002] t1
           LEFT JOIN [dbo.test_db_003] t2 ON t1.[id]=t2.[itmid] 
) x
WHERE x.[id] = 5

Note that the -1 is because ROW_NUMBER() starts at 1 instead of 0 and you specifically mentioned a zero-indexed array.

Try this... Though I'm not sure on your table structure

Declare @Temp table
(
    id int,
    Name varchar(20)
)
Insert into @Temp 
    select 1, 'Bob'
union all
    select 2, 'Mark'
union all
    select 3, 'Shaun'
union all
    select 4, 'Ryan'
union all
    select 5, 'Steve'
union all
    select 6, 'Bryan'
union all
    select 7, 'Henry'

Declare @Temp2 table
(
    iid int,
    itmid int,
    Name varchar(20)
)
Insert into @Temp2
    select 1, 3, 'Thing'
union all
    select 2, 2, 'This'
union all
    select 3, 5, 'That'
union all
    select 4, 1, 'They'
union all
    select 5, 3, 'There'
union all
    select 6, 5, 'Though'
union all
    select 7, 6, 'Thought'

SELECT t1.[id], Row_Number() OVER (Order by t1.[id]) as RowNum
FROM @Temp t1
LEFT JOIN @Temp2 t2 ON t1.[id]=t2.[itmid] 
ORDER BY t1.[id] ASC;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top