2011-11-11 58 views
1

我正在使用SQL Server數據庫。說,我有一個選擇返回一個ID數組。我可以找出(與SQL)在該數組中的ID等於N的順序?SQL在特定ID中選擇序號索引

這是我的意思。這是我的實際選擇:

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; 

說,這將返回的ID下面的數組:

13, 7, 34, 5, 2, 14 

,並說我需要知道什麼索引是數組中的ID = 5(答案是3,如果圖13是索引0,7 =索引1,34 =索引2,5 =變爲索引3)

回答

1

嘗試使用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; 

更多關於在這裏http://msdn.microsoft.com/en-us/library/ms186734.aspx

+0

衛生署,你打我吧! –

+0

非常感謝。我想知道SQL是值得的,呵呵;)我發誓我有一天會這樣! – ahmd0

+0

很高興能幫到你:) – misha

1

試試這個:

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 

注意,-1是因爲ROW_NUMBER()從1開始,而不是0和你特別提到零索引數組。

+0

謝謝。我必須給第一個人正確的答案。但是,仍然感謝張貼。我很欣賞它! – ahmd0

1

嘗試......雖然我不知道你的表結構

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; 
+0

謝謝,這也是一個正確的答案。 – ahmd0