按SQL按字符串排序
在SQL中,是否可以按字符串而不是按如下升序/降序对查询排序按SQL按字符串排序,sql,Sql,在SQL中,是否可以按字符串而不是按如下升序/降序对查询排序 Select * From people ORDER BY names (john, steve, bob, bill) 在标准SQL中,需要一个case语句 Select * From people ORDER BY (case when names = 'john' then 1 when names = 'steve' then 2 when names = 'bob
Select * From people ORDER BY names (john, steve, bob, bill)
在标准SQL中,需要一个
case
语句
Select *
From people
ORDER BY (case when names = 'john' then 1
when names = 'steve' then 2
when names = 'bob' then 3
when names = 'bill' then 4
else 5
);
有些SQL引擎有实现这一点的快捷方式,但您没有提到您正在使用哪个数据库
例如,在MySQL中,您可以执行以下操作:
order by field(names, 'john', 'steve', 'bob', 'bill');
另一种方法是使用charIndex,即
ORDER BY CharIndex('|'+names+'|','|john|steve|bob|bill|')
Charindex将返回找到的名称的位置,在大列表中找到的越早,Charindex返回的数字越低@user3208629。是的,如果有两个人被称为约翰,这就行了。两者都将首先出现在列表中。