简体   繁体   English

SQL排序字符串和数字

[英]SQL Sorting Strings and Numbers

If I have a list of 1,2,3,4,5,K and I want it ordered like K,1,2,3,4,5 how can I do this in SQL? 如果我有一个1,2,3,4,5,K列表1,2,3,4,5,K并且希望像K,1,2,3,4,5那样进行排序K,1,2,3,4,5该如何在SQL中执行此操作? Those values are the only ones in the SQL table. 这些值是SQL表中唯一的值。 This is in MySQL, but other databases are also welcomed. 这是在MySQL中,但也欢迎使用其他数据库。

There's no integer dection function in mysql, so you'll have to do something like this. mysql中没有整数运算函数,因此您必须执行类似的操作。 Assuming your column is varchar or the like, you could something simple like this 假设您的列是varchar之类,您可以像这样简单

ORDER BY CASE WHEN field REGEXP '^-?[0-9]+$' THEN field ELSE '0'+field END

In Oracle, you could do: 在Oracle中,您可以执行以下操作:

ORDER BY CASE WHEN column='K' THEN 0 ELSE TO_NUMBER(column) END

Other systems presumably have similar constructs. 其他系统可能具有类似的构造。

If you need to sort the SELECT's result, then you might just declare your custom sorting rules in ORDER BY statement. 如果需要对SELECT的结果进行排序,则可以只在ORDER BY语句中声明自定义排序规则。

Here's an example: http://www.emadibrahim.com/2007/05/25/custom-sort-order-in-a-sql-statement/ 这是一个示例: http : //www.emadibrahim.com/2007/05/25/custom-sort-order-in-a-sql-statement/

The idea is to assign your own priority to each item. 这个想法是给每个项目分配自己的优先级。

Bear in mind that it might be dependant on the actual SQL server. 请记住,它可能取决于实际的SQL Server。

Here's one that works in SQLite: 这是在SQLite中工作的一种:

 select v1.* from (
   select t3.*, (case when value = 'K' then '0' else value end) normalized_val 
   from t3) v1 
 order by v1.normalized_val;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM