【问题标题】:Order by in postgresql在 postgresql 中排序
【发布时间】:2014-12-08 10:28:25
【问题描述】:

我将用示例 ddl 和数据解释我的问题

create table foo ( itm text);


insert into foo VALUES  ('ZZZZ8 AAA'),
                        ('YYYY8 BBB'),
                        ('XXXX7 AAA'),
                        ('WWWW GGG'),
                        ('VVVV7 III'),
                        ('UUUU2 GGG');

如果我执行SELECT * FROM FOO

itm
text
------------------
ZZZZ8 AAA
YYYY8 BBB
XXXX7 AAA
WWWW GGG    
VVVV7 III
UUUU2 GGG

所以我的问题是如何根据最后 3 个字符(例如AAABBB 等)对结果进行排序?


预期输出

itm
text
---------------
ZZZZ8 AAA
XXXX7 AAA
YYYY8 BBB
WWWW GGG
UUUU2 GGG
VVVV7 III

【问题讨论】:

    标签: sql postgresql sql-order-by


    【解决方案1】:

    您可以在 ORDER BY 子句中使用RIGHT function

    SELECT itm, right(itm, 3)
    FROM foo
    ORDER BY right(itm, 3) ASC;
    

    SqlFiddle here

    【讨论】:

      【解决方案2】:
          SELECT itm 
          FROM   foo 
          ORDER BY substring(itm from char_length(trim(itm))-3 for 3)
      

      substring and char_length

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 1970-01-01
        • 2019-08-08
        • 1970-01-01
        • 2017-09-05
        • 1970-01-01
        • 2018-06-11
        相关资源
        最近更新 更多