【问题标题】:Order column by custom pattern按自定义模式排序列
【发布时间】:2020-01-02 14:36:06
【问题描述】:

我正在尝试订购发票数据列。发票编码字段由以下部分组成:

  1. 大写字母(例如 A-Z)
  2. 实际年份(例如 19)
  3. 反斜杠 (/)
  4. 发票编号(例如 100)

实例:F19/1234

此时我正在使用以下查询按发票编码订购

select * from `invoices` 
order by LENGTH(codification) desc, `codification` desc 

这适用于 2019 年的发票,问题是 2020 年的发票编号重置为 0,因此此订购失败。

现在我有以下内容

  • F19/102
  • F19/101
  • F19/100
  • F20/1
  • F20/0

关于如何按年份和发票编号降序排列的任何想法?

我已尝试按 REGEX_SUBSTRING 进行排序,但这不起作用,我认为此查询没有任何作用...

select * from `invoices` 
order by REGEXP_SUBSTR(`codification`, '[0-9]+(?=\/)') desc, REGEXP_SUBSTR(`codification`, '([a-z0-9_-]*[\/]?)$') desc

我想要完成的订单是(按年份和发票编号递减)

  • F20/1
  • F20/0
  • F19/102
  • F19/101
  • F19/100

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    我认为这会奏效:

    order by codification desc
    

    当 2020 年的发票数量超过 10 个时,您将遇到问题。处理该问题:

    order by substring_index(codification, '/', 1),
             substring_index(codification, '/', -1) + 0
    

    【讨论】:

      【解决方案2】:

      为什么不尝试直接按元素排序。例如。 order by year desc, invoice_number desc?

      可能你也需要为大写字母添加元素。

      【讨论】:

        猜你喜欢
        • 2014-03-04
        • 2017-07-30
        • 2021-04-02
        • 2014-12-09
        • 2022-01-08
        • 2019-03-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        相关资源
        最近更新 更多