您好我正在使用IN运算符进行简单查询。我正在使用以下查询
SELECT CustID FROM Customer WHERE CustID in (6,34,5,4,3,2,1)
现在显示以下订单
custId
1
2
3
4
5
6
34
但我希望结果与我在IN
条款中传递的序列相同。
答案 0 :(得分:3)
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
答案 1 :(得分:2)
试试这个查询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,')
答案 2 :(得分:0)
标准SQL未在select
语句或in
子句中指定默认顺序。这些行将以DBMS想要的任何顺序返回。
如果您想强制订单具体,您需要使用order-by子句。
某些SQL 实现可能允许配置它,但不能定期配置任何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
但它非常丑陋而且效率不高。
答案 3 :(得分:0)
你不能,如果你想要那样,你需要一个像'showorder'这样的新领域,你可以在其上订购你的结果:
SELECT CustID FROM Customer WHERE CustID IN (6,34,5,4,3,2,1) ORDER BY showorder
答案 4 :(得分:0)
试试这个 -
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
答案 5 :(得分:0)
使用具有有序值的拆分字符串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]
OR
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]