您好我正在使用带有 IN 运算符的简单查询。我正在使用以下查询
SELECT CustID FROM Customer WHERE CustID in (6,34,5,4,3,2,1)
现在它显示以下订单
custId
1
2
3
4
5
6
34
IN
但我希望结果与我在子句中传递的序列相同。
您好我正在使用带有 IN 运算符的简单查询。我正在使用以下查询
SELECT CustID FROM Customer WHERE CustID in (6,34,5,4,3,2,1)
现在它显示以下订单
custId
1
2
3
4
5
6
34
IN
但我希望结果与我在子句中传递的序列相同。
SELECT CustID FROM Customer WHERE CustID in (6,34,5,4,3,2,1)
ORDER BY CASE WHEN CustId = 34
THEN 5.5
ELSE CustId
END DESC
试试这个 Query Ramdas ......
SELECT CustID FROM Customer WHERE CustID in (6,34,5,4,3,2,1)
ORDER BY CHARINDEX(','+CAST(CustID as varchar(MAX))+',', ',6,34,5,4,3,2,1,')
试试这个——
DECLARE @id TABLE
(
i INT IDENTITY(1,1)
, id INT
)
INSERT INTO @id (id)
VALUES (6),(34),(5),(4),(3),(2),(1)
SELECT c.CustID
FROM dbo.Customer c
JOIN @id i ON i.id = c.CustID
ORDER BY i.i
使用带有有序值的拆分字符串 CTE。因此,您将能够对任何数据集进行排序
DECLARE @test nvarchar(100) = '6,34,5,4,3,2,1';
;WITH cte AS
(
SELECT SUBSTRING(@test , 0, CHARINDEX( ',', @test)) AS val ,
CAST(STUFF (@test + ',' , 1, CHARINDEX( ',', @test), '') AS nvarchar(100 )) AS stval,
1 AS [level]
UNION ALL
SELECT SUBSTRING(stval , 0, CHARINDEX( ',', stval)),
CAST(STUFF (stval, 1, CHARINDEX(',' , stval ), '' ) AS nvarchar(100 )),
[level] + 1
FROM cte
WHERE stval != ''
)
SELECT c2.CustID
FROM dbo.Customer c2 JOIN cte c ON c2.CustID = c.val
ORDER BY c.[level]
SQLFiddle上的演示
您也可以将 CTE 包装在函数中
CREATE FUNCTION dbo. SplitStrings_CTE(@List nvarchar( 1000), @Delimiter nvarchar(1 ))
RETURNS TABLE
AS
RETURN
WITH cte AS
(
SELECT SUBSTRING(@List , 0 , CHARINDEX (@Delimiter, @List)) AS val ,
CAST(STUFF (@List + @Delimiter, 1 , CHARINDEX (@Delimiter, @List), '') AS nvarchar (1000)) AS stval, 1 AS [level]
UNION ALL
SELECT SUBSTRING(stval , 0 , CHARINDEX (@Delimiter, stval)),
CAST(STUFF (stval , 1, CHARINDEX( @Delimiter , stval ), '' ) AS nvarchar(1000 )), [level] + 1
FROM cte
WHERE stval != ''
)
SELECT REPLACE(val , ' ' , '' ) AS val, [level]
FROM cte
使用函数的 SELECT 语句
DECLARE @test nvarchar(100) = '6,34,5,4,3,2,1';
SELECT CustID
FROM dbo.Customer c2 JOIN (SELECT val, [level] FROM dbo.SplitStrings_CTE(@test, ',')
) c ON c2.CustID = c.val
ORDER BY c.[level]
或者
DECLARE @test nvarchar(100) = '6,34,5,4,3,2,1';
SELECT CustID
FROM dbo.Customer c2 CROSS APPLY dbo.SplitStrings_CTE(@test, ',') c
WHERE c2.CustID = c.val
ORDER BY c.[level]
标准 SQL 没有在select
语句或in
子句中指定默认顺序。这些行将以 DBMS 想要的任何顺序返回。
如果您想强制执行特定的顺序,则需要使用 order-by 子句。
一些 SQL实现可能允许配置它,但不是我经常使用的任何一个。最坏的情况,您可以尝试以下方法:
select 1 as x, custid from customer where custid = 6
union all select 2 as x, custid from customer where custid = 34
union all select 3 as x, custid from customer where custid = 5
order by x
但它非常丑陋而且效率不高。
你不能,如果你想让这种情况发生,你需要一个新的字段,比如“showorder”之类的,你可以在上面订购你的结果:
SELECT CustID FROM Customer WHERE CustID IN (6,34,5,4,3,2,1) ORDER BY showorder