gpt4 book ai didi

sql - 如何先按数字排序查询,然后在同一字段中按字符串排序

转载 作者:行者123 更新时间:2023-11-29 13:33:49 25 4
gpt4 key购买 nike

我在 PostgreSQL 9.0 中有一个数据库,它有一个带有字符串字段的表来存储客户端代码。这些代码是字母数字,可以字母或数字开头,例如 1, 2, A0001-4, A0001-2, 10

我想先按数字排序,然后按字符串排序,比如

1, 2, 10, A0001-2, A0001-4

我使用 to_number(fields, '99999999') 执行此操作,例如:

SELECT * FROM empleados ORDER BY to_number(legajo, '99999999'), legajo

但是当代码像'',没有数字时,查询失败。

我能做什么?

最佳答案

您可以使用 case 语句来查找数字:

select *
from empleados
order by (case when legajo not similar to '%[^0-9]%' then 1 else 0 end) desc,
(case when legajo not similar to '%[^0-9]%' then to_number(legajo, '999999999') end),
legjo;

similar to 表达式表示所有字符都是数字。

编辑:

修正了语法错误。你可以测试这个:

with empleados as (
select 'abc' as legajo union all
select '123'
)
select *
from empleados
order by (case when legajo not similar to '%[^0-9]%' then 1 else 0 end) desc,
(case when legajo not similar to '%[^0-9]%' then to_number(legajo, '999999999') end),
legajo;

SQLFiddle 是 here .

关于sql - 如何先按数字排序查询,然后在同一字段中按字符串排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com