如何使用等于0的值自然地对文本进行排序?

时间:2012-07-02 09:20:44

标签: sql sqlite sorting natural-sort

我想从sql:

对这个测试表进行排序
CREATE TABLE test (
    _id integer primary key autoincrement,
    val text
);

insert into test (_id, val) values ("49","-10");
insert into test (_id, val) values ("53","-6");
insert into test (_id, val) values ("63","-6");
insert into test (_id, val) values ("9","-5");
insert into test (_id, val) values ("56","-5");
insert into test (_id, val) values ("73","-5");
insert into test (_id, val) values ("38","-4");
insert into test (_id, val) values ("52","-4");
insert into test (_id, val) values ("55","-4");
insert into test (_id, val) values ("64","-4");
insert into test (_id, val) values ("81","-4");
insert into test (_id, val) values ("50","-3");
insert into test (_id, val) values ("60","-3");
insert into test (_id, val) values ("78","-3");
insert into test (_id, val) values ("27","-2");
insert into test (_id, val) values ("1","80");
insert into test (_id, val) values ("2","85");
insert into test (_id, val) values ("3","100");
insert into test (_id, val) values ("4","120");
insert into test (_id, val) values ("5","-");
insert into test (_id, val) values ("6","0");
insert into test (_id, val) values ("7","0 (init)");
insert into test (_id, val) values ("8","-1");
insert into test (_id, val) values ("23","1");
insert into test (_id, val) values ("67","3");
insert into test (_id, val) values ("14","4");
insert into test (_id, val) values ("16","4");
insert into test (_id, val) values ("22","4");
insert into test (_id, val) values ("61","4");
insert into test (_id, val) values ("37","5");
insert into test (_id, val) values ("51","5");
insert into test (_id, val) values ("76","5");
insert into test (_id, val) values ("32","6");
insert into test (_id, val) values ("35","6");
insert into test (_id, val) values ("71","6");
insert into test (_id, val) values ("88","6");
insert into test (_id, val) values ("18","7");
insert into test (_id, val) values ("44","7");
insert into test (_id, val) values ("39","9");
insert into test (_id, val) values ("90","9");
insert into test (_id, val) values ("91","9");
insert into test (_id, val) values ("69","16");
insert into test (_id, val) values ("105","-");
insert into test (_id, val) values ("36","0");
insert into test (_id, val) values ("65","0");
insert into test (_id, val) values ("75","0");
insert into test (_id, val) values ("106","d");
insert into test (_id, val) values ("43","noise");

从这里使用修改过的sql: SQLite sorting question

select _id, case when cast(val as number) = 0 then val when cast(val as number) <>0 then cast(val  as number) end as sorting from test order by sorting;

我得到了几乎完美的结果,但是:0值不在正负之间

1 个答案:

答案 0 :(得分:0)

编辑:抱歉,这是针对MySQL的。也许你可以为SQLite调整它?

可能不是最漂亮的,但是这会将任何不是(签名)号码的“val”排序到最后。只要确保它获得的值高于最高数字。

select
  _id,
  val
from test
order by 
case when val NOT REGEXP '^-{0,1}[0-9]{1,}$' then 999999 else
cast(val as signed integer)
end