任何标准SQL表达式,用于对IN表达式进行排序

时间:2011-08-09 06:47:46

标签: sql

  

可能重复:
  SQL - order by list order

是否有任何标准SQL表达式可以完全基于IN表达式对结果进行排序。例如,返回以下查询的结果,以便串行返回2,4,6,8?

SELECT * FROM SOMETABLE WHERE ID IN (2, 4, 6, 8)

3 个答案:

答案 0 :(得分:1)

我能想到的最接近的事情就是在原始顺序及其顺序等级的情况下对一个表进行JOIN而不是IN。

SELECT * FROM SOMETABLE INNER JOIN SOMETABLE2 ...  etc
ORDER BY SOMETABLE2.original

答案 1 :(得分:1)

如果您完全控制了SQL渲染,请使用CASE表达式:

ORDER BY CASE ID 
-- render WHEN clauses in the desired order
WHEN 2 THEN 1 
WHEN 4 THEN 2
WHEN 6 THEN 3
WHEN 8 THEN 4
END

答案 2 :(得分:0)

假设您可以将ID作为固定的分隔字符串传递,您可以执行以下操作:

-- Populate a number table
DECLARE @Temp Table(Number int)

INSERT INTO @Temp VALUES(1)
INSERT INTO @Temp VALUES(2)
INSERT INTO @Temp VALUES(3)
INSERT INTO @Temp VALUES(4)
INSERT INTO @Temp VALUES(5)
INSERT INTO @Temp VALUES(6)
INSERT INTO @Temp VALUES(7)
INSERT INTO @Temp VALUES(8)
INSERT INTO @Temp VALUES(9)
INSERT INTO @Temp VALUES(10)

SELECT TOP 8000 Number = IDENTITY(int,1,1) INTO [dbo].Numberos FROM @TEMP t1, @TEMP t2, @TEMP t3, @TEMP t4

ALTER TABLE [dbo].[Numbers] ADD CONSTRAINT [PK_Numbers] PRIMARY KEY CLUSTERED  ([Number])

-- This function splits a fixed delimited string into a table object
CREATE FUNCTION [dbo].[fixstring_single](@str text, @itemlen tinyint) 
RETURNS TABLE 
AS 
RETURN (SELECT listpos = n.Number, 
str = substring(@str, (@itemlen + 1) * (n.Number - 1) + 1, @itemlen) 
FROM Numbers n 
WHERE n.Number <= (datalength(@str)+1) / (@itemlen+1)) 

DECLARE @ids varchar(100);
SET @ids = '00002 00001 00004';

-- Join to the number table ordered by the posisiton in the ids string
SELECT * FROM TestT INNER JOIN fixstring_single(@ids, 5) S ON TestT.ID = S.Str ORDER BY S.listpos