Как получить результат таблицы содержит числовые и строки, используя условие where в postgres - PullRequest
0 голосов
/ 11 июля 2019

У меня есть таблица, как показано ниже

enter image description here

Когда я выбираю item_no> '1623G' из таблицы выше

Я хочувыведите результат ниже

1623H | 1623I | 1666 | 1674 | 1912 | 1952 | 1953

Я пытаюсь выполнить команду ниже

select * from t where substring(item_no,'([0-9]+)') :: int  > 1623G

Но это не дает результата, пожалуйста, помогите

Ответы [ 2 ]

1 голос
/ 11 июля 2019

Я бы пошел путем регулярного выражения:

демо: дб <> скрипка

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)

Разделение обоих значений (значения строки и сравниваемого) на обе части (цифры и не цифры) и сравнение каждой части по отдельности.

Мне любопытно, есть ли лучшее решение.

1 голос
/ 11 июля 2019

Вы можете использовать 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)
...