2014-10-06 74 views
-1

我有一個查詢,其中使用了「In」子句。 現在我希望按照與In子句相同的順序設置結果集。 例如 -通過「In clause」排序

select Id,Name from mytable where id in (3,6,7,1) 

結果集:

|Id | Name | 
------------ 
| 3 | ABS | 
| 6 | NVK | 
| 7 | USD | 
| 1 | KSK | 

我不希望使用任何臨時表。 在一個查詢中可以實現目標嗎?

+0

認沽3 ,6,7,1在表中,INNER JOIN到它,ORDER BY它 – 2014-10-06 14:02:04

+0

這是面試的問題嗎?你爲什麼要這麼做?爲什麼只使用1個查詢?如果這是一個真正的要求,你可能有成千上萬的行,而不是僅僅4個。 – Meet 2014-10-07 09:42:48

+0

@Meet這不是面試問題,而是一個工作的同事欺騙了我,並且他爲我們的團隊採訪了面子.-) – 2014-10-30 13:24:59

回答

2

在T-SQL,您可以使用做一個大case

select Id, Name 
from mytable 
where id in (3, 6, 7, 1) 
order by (case id when 3 then 1 when 6 then 2 when 7 then 3 else 4 end); 

或者與charindex()

order by charindex(',' + cast(id as varchar(255)) + ',', 
        ',3,6,7,1,') 
+0

我認爲他只需要在sybase中使用此功能,而不是在MSSQL中。所以沒有charindex將工作 – 2014-10-06 14:03:49

+1

@AnkitBajpai。 。 。 Sybase支持'charindex()'。 – 2014-10-06 15:08:50

+0

是的,Sybase ASE 15確實支持charindex() - 我在開始時嘗試使用charindex,但可能是錯誤地思考。但我用戈登的邏輯得到了我的結果。謝謝 ! – 2014-10-08 07:22:36

3

您可以使用CTE以及

with filterID as 
(
    3 ID, 1 as sequence 
    union 
    6, 2 
    union 
    7, 3 
    union 
    1, 4 
) 

select mytable.* from mytable 
inner join filterID on filterID.ID = mytable.ID 
order by filterID.sequence ;