【问题标题】:How to order sql results starting with a certain string如何对以某个字符串开头的 sql 结果进行排序
【发布时间】:2014-05-23 17:54:26
【问题描述】:

我是 SQL 新手,我真的需要你的帮助,谢谢你提前 :)

我正在使用SQL从表(动物)中选择一个列(animal_name),其内容包含某个字符串(例如'cat'),示例结果:

mycat, hercat, catKitty, catLili, acata, bcatb

现在我希望结果首先显示以'cat'开头的字符串,然后显示剩余的字符串ASC,我想要的示例结果:

catKitty, catLili, acata, bcatb, hercat, mycat

现在我才知道如何使用 LIKE 来选择包含 'cat' 的结果:

select animal_name from animal where animal_name like '%cat%';

但我不知道如何按结果排序。你能给出一些建议吗?再次感谢:)

【问题讨论】:

    标签: sql sql-order-by


    【解决方案1】:
    select animal_name 
    from animal 
    where animal_name like '%cat%' --test if name contains cat
    order by
     case when animal_name like 'cat%' then 0 else 1 end, -- order with name starting with cat first
     animal_name -- then by name
    

    SqlFiddle

    【讨论】:

    • 这正是我想要的,非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 2014-12-02
    • 1970-01-01
    • 2015-08-30
    • 2021-11-22
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多