【发布时间】:2019-07-11 08:45:05
【问题描述】:
我有一张如下表
当我从上表中选择 item_no>'1623G' 时
我想打印下面的结果
1623H | 1623I | 1666 | 1674 | 1912 | 1952 | 1953
我正在尝试以下命令
select * from t where substring(item_no,'([0-9]+)') :: int > 1623G
但它没有给出结果 请帮忙
【问题讨论】:
我有一张如下表
当我从上表中选择 item_no>'1623G' 时
我想打印下面的结果
1623H | 1623I | 1666 | 1674 | 1912 | 1952 | 1953
我正在尝试以下命令
select * from t where substring(item_no,'([0-9]+)') :: int > 1623G
但它没有给出结果 请帮忙
【问题讨论】:
我会采用正则表达式的方式:
WITH cte AS (
SELECT
item_no,
regexp_replace(item_no, '\D', '', 'g')::int AS digit,
regexp_replace(item_no, '\d', '', 'g') AS nondigit,
regexp_replace('200a', '\D', '', 'g')::int AS compare_digit,
regexp_replace('200a', '\d', '', 'g') AS compare_nondigit
FROM t
)
SELECT
item_no
FROM
cte
WHERE
(digit > compare_digit) OR (digit = compare_digit AND nondigit > compare_nondigit)
将两个值(行值和比较值)拆分为两个部分(数字和非数字)并分别比较每个部分。
我很好奇是否有更好的解决方案。
【讨论】:
您可以将 CONVERT_TO 用作:
testdb1=# CREATE TABLE t (item_no varchar(20));
CREATE TABLE
testdb1=# INSERT INTO t VALUES('2'),('20'),('200'),('200a'),('200b'),('200c'),('2000');
INSERT 0 7
testdb1=# SELECT * FROM t;
item_no
---------
2
20
200
200a
200b
200c
2000
(7 rows)
testdb1=# select * from t where substring(convert_to(item_no,'SQL_ASCII')::text,3)::int > substring(convert_to('2a','SQL_ASCII')::text,3)::int;
item_no
---------
200
200a
200b
200c
2000
(5 rows)
testdb1=# select * from t where substring(convert_to(item_no,'SQL_ASCII')::text,3)::int > substring(convert_to('150','SQL_ASCII')::text,3)::int;
item_no
---------
200
200a
200b
200c
2000
(5 rows)
【讨论】: