【问题标题】:SQLITE: How do I sort a String column containing values 1-99 and letters a-z, with numbers first then lettersSQLITE:如何对包含值 1-99 和字母 a-z 的字符串列进行排序,首先是数字,然后是字母
【发布时间】:2015-12-09 06:59:37
【问题描述】:

我想要一个字符串列的排序顺序,如下所示(数字在前,字母在后):

1
2
...
10
11
...
A
B
C
...

这是我当前的查询

SELECT * FROM PAGES_VIEW ORDER BY chapterTitle

不幸的是,这会导致以下排序(10 在 2 之前)

1
10
2
20
...
A
B
...

如何实现我想要的订单?

编辑:将我的 CAST 删除为整数以避免混淆。

【问题讨论】:

    标签: sql database sqlite sorting


    【解决方案1】:

    您应该使用case 语句来获得所需的ordering。

    Fiddle with sample data

    select * from pages_view 
    order by (case when cast(chaptertitle as integer) = chaptertitle then 1
             else 0 end) desc, cast(chaptertitle as integer), chaptertitle
    

    【讨论】:

    • 可能希望在末尾有第二个排序术语 chaptertitle,因此它首先按类型(根据您的案例语句为 0 或 1)排序,然后按实际文本排序。
    • @jklemmack.. else 部分处理文本部分。
    • 真的,你只是在对“0”和“1”进行排序。如果数据不是按顺序排列的,那么排序是错误的。用以下数据调整你的小提琴。虽然您的答案适用于明确的问题,但它做出了一些假设,我不希望其他人稍后被误导:插入 t values('Q'),('R'),('50'),( '2'),('10'),('C'),('D'),('25'),('F'),('100')
    • @jklemmack .. 我意识到我的错误。现在更正它。
    猜你喜欢
    • 2012-08-12
    • 2017-05-11
    • 2019-02-14
    • 2023-03-26
    • 2015-01-31
    • 2022-01-01
    • 2016-10-28
    • 2019-03-28
    相关资源
    最近更新 更多