感觉就像一个愚蠢的问题。
我有以下查询
select 'Cardiac - ACS' as a
union
select 'Cardiac - All' as a
order by a
我希望第二行“Cardiac - All”首先替换“连字符”字符。我该怎么替换它? (以及如何在Postgres中找出符号的顺序及其优先级?)
答案 0 :(得分:1)
排序顺序取决于您的语言环境,尤其是collation。找到您的设置:
SHOW lc_collate;
在C
语言环境中,字符根据其字节值进行排序。这些字符在连字符('-'
)之前排序:
SELECT chr(g)
FROM generate_series (33,ascii('-')) g
chr
---
!
"
#
$
%
&
'
(
)
*
+
,
-
对于其他排序规则, 不 为true。测试:
SELECT g, chr(g)
FROM generate_series (33,ascii('-')) g
order by chr(g) COLLATE "C"
连字符的十进制ASCII值为45.
移除COLLATE "C"
以查看您的当前区域设置的效果。
要在排序规则中查找基本候选字符,请运行:
SELECT g, chr(g)
FROM generate_series (1,255) g
ORDER BY chr(g);
答案 1 :(得分:1)
如果存在任意排序要求,则创建要排序的列:
select a, (left(a, position('-' in a)), arbitrary_order)
from (
select 'Cardiac - ACS' as a, 9 as arbitrary_order
union
select 'Cardiac - All', 0
) s
order by 2, 1
;
a | row
---------------+-----------------
Cardiac - All | ("Cardiac -",0)
Cardiac - ACS | ("Cardiac -",9)
arbitrary_order
列的默认值类似于9或999,任意情况的值都会更低。
或测试是否存在' - All'字符串
select a, (
left(a, position('-' in a)),
substring(a from position('-' in a)) != '- All'
)
from (
select 'Cardiac - ACS' as a
union
select 'Cardiac - All'
) s
order by 2, 1
;
a | row
---------------+-----------------
Cardiac - All | ("Cardiac -",f)
Cardiac - ACS | ("Cardiac -",t)