【问题标题】:How to get the result of table contains numeric and strings using where condition in postgres如何使用postgres中的where条件获取表的结果包含数字和字符串
【发布时间】: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

但它没有给出结果 请帮忙

【问题讨论】:

    标签: postgresql postgresql-9.5


    【解决方案1】:

    我会采用正则表达式的方式:

    demo:db<>fiddle

    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)
    

    将两个值(行值和比较值)拆分为两个部分(数字和非数字)并分别比较每个部分。

    我很好奇是否有更好的解决方案。

    【讨论】:

    • 我已经通过传递 '0005' 进行了尝试,但它正在返回行,但它不应该。
    • @Vivek 为什么不呢?完全没问题。 0005 == 5 和 20、200、2000 更大
    • 完美,这是我的误会。
    【解决方案2】:

    您可以将 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)
    

    【讨论】:

    • 如果一条记录的值为“3”,另一条记录的值为“4”,那么在我的情况下,它将返回另外两条记录为“3”和“4”,其中“2h”和“2d”。我正在使用 PG 11.4,在 9.5 中不确定。
    • @Vivek 我喜欢你的想法,但它确实行不通...dbfiddle.uk/…
    • @vivek 在版本 11.4 中尝试了它提供除 1623G 之外的所有值
    • @S-Man 感谢您的通知,我已经更新了答案,现在它将处理实际字符串到 ascii 的转换,然后是条件过滤器
    • @Vivek:还是不行。尝试 200a 而不是 2a。那么你会错过 2000 dbfiddle.uk/…
    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多