2013-05-05 35 views
1

我有一個類似於下面的查詢,我希望記錄以與在'in'函數中指定的id相同的順序返回。根據函數中的SQL內部的順序對列進行排序

SELECT * FROM table 1 where id in(12,6,4,3,13) 

我可以單獨使用sql嗎?還是我需要編寫自己的排序函數?

+0

插入將它們轉換爲具有兩列的臨時表或表值參數。 'id'和'SortOrder'並加入而不是使用'in'。然後你可以在第二欄訂購。 – 2013-05-05 16:40:02

回答

2

可以使用CASE來記錄自定義排序,

ORDER BY CASE WHEN ID = 12 THEN 1 
       WHEN ID = 6 THEN 2 
       WHEN ID = 4 THEN 3 
       WHEN ID = 3 THEN 4 
       WHEN ID = 13 THEN 5 
       ELSE 6 
     END, ID 
+0

多數民衆贊成現在罰款..但我有我自己的查詢,如果「列表」不是固定的,有沒有什麼辦法,我們可以根據列表進行排序? – 2013-05-05 16:31:57

+0

是可擴展的解決方案嗎?說像100-10k ID? – thunderbird 2013-05-05 16:33:10

+0

@AmitSingh然後您可以爲此創建動態SQL,或者在應用程序級別創建一條生成條件排序的語句。 – 2013-05-05 16:33:19

3

創建一個表,你的ID,然後用另一個身份列加入到表,訂貨。

大概如果你有10K的ID,他們不會被手動輸入,因此可以建立排序/連接表以不同的方式。還應該更加效率比使用大in

create table #tempID(idSort int identity(1,1), id int) 
insert into #tempID(id) 
select 12 union all 
select 6 union all 
select 4 union all 
select 3 union all 
select 13 

select * from table t1 
    inner join #tempID t2 
     on t1.id = t2.id 
order by t2.idSort 

要動態創建排序表,你需要這個功能(或類似):

create FUNCTION [dbo].[comma_sep_var_intSort] (@list nvarchar(MAX)) 
    RETURNS @tbl TABLE (idSort int identity(1,1), id int NOT NULL 
) AS 
BEGIN 
    DECLARE @pos  int, 
      @nextpos int, 
      @valuelen int 

    SELECT @pos = 0, @nextpos = 1 

    WHILE @nextpos > 0 
    BEGIN 
     SELECT @nextpos = charindex(',', @list, @pos + 1) 
     SELECT @valuelen = CASE WHEN @nextpos > 0 
           THEN @nextpos 
           ELSE len(@list) + 1 
         END - @pos - 1 
     INSERT @tbl (id) 
     VALUES (cast(substring(@list, @pos + 1, @valuelen) as int)) 
     SELECT @pos = @nextpos 
    END 
    RETURN 
END 

然後加入這樣的:

declare @idList varchar(max) 

set @idLIst = '12,6,4,3,13' 

    select * from table t1 
     inner join [dbo].[comma_sep_var_int](@idList) t2 
      on t1.id = t2.id 
    order by t2.idSort 
+0

+1使其接近動態 – 2013-05-06 03:58:19

+0

如果你想要它動態的,你可能需要一個函數。 – dantibb 2013-05-06 11:41:32

相關問題