gpt4 book ai didi

sql - 如何按在 SQL Server 中输入的顺序排序?

转载 作者:行者123 更新时间:2023-12-02 05:47:27 25 4
gpt4 key购买 nike

我正在使用 SQL Server 并尝试查找结果,但我希望按照输入条件时的相同顺序获取结果。

我的代码:

SELECT 
AccountNumber, EndDate
FROM
Accounts
WHERE
AccountNumber IN (212345, 312345, 145687, 658975, 256987, 365874, 568974, 124578, 125689) -- I would like the results to be in the same order as these numbers.

最佳答案

这是一种内联方法

示例

Declare @List varchar(max)='212345, 312345, 145687, 658975, 256987, 365874, 568974, 124578, 125689'

Select A.AccountNumber
,A.EndDate
From Accounts A
Join (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = v.value('(./text())[1]', 'int')
From (values (convert(xml,'<x>' + replace(@List,',','</x><x>')+'</x>'))) x(n)
Cross Apply n.nodes('x') node(v)
) B on A.AccountNumber = B.RetVal
Order By B.RetSeq

EDIT - the subquery Returns

RetSeq  RetVal
1 212345
2 312345
3 145687
4 658975
5 256987
6 365874
7 568974
8 124578
9 125689

关于sql - 如何按在 SQL Server 中输入的顺序排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51030750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com