【问题标题】:CASE Statement for Order By Clause with Multiple Columns具有多列的 Order By 子句的 CASE 语句
【发布时间】:2021-07-20 14:34:44
【问题描述】:

我希望 Order by 语句根据条件更改列排序顺序。

例如,如果您有 A、B、C、D 列并且条件值作为参数 (pType) 输入

  • 如果 pType = 1 排序 A、B、C、D

  • 如果 pType = 2 排序 B、C、D、A

  • 如果 pType = 3 C、A、B、D

在应用和使用语句时按大小写排序如下。 发生错误。

Order by
Case
when pType = 1 then A, B, C, D
when pType = 2 then B, C, D, A
when pType = 3 then C, A, B, D

我应该如何使用它?

感谢您的帮助。

【问题讨论】:

    标签: oracle


    【解决方案1】:

    看看这是否有效。

    with t1_ as
    (
      select 1 as ptype, 10 as a, 5  as b, 20 as c from dual union all
      select 1 as ptype, 6  as a, 10 as b, 21 as c from dual union all
      
      select 2 as ptype, 20 as a, 2 as b, 16 as c from dual union all
      select 2 as ptype, 100 as a, 1 as b, 90 as c from dual
    )
    
    select 
    * 
    from t1_
    order by
    case when ptype = 1 then a end asc,
    case when ptype = 1 then b end asc,
    case when ptype = 1 then c end asc,
    
    case when ptype = 2 then b end asc,
    case when ptype = 2 then c end asc,
    case when ptype = 2 then a end asc
    

    小提琴网址供参考https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=d567ebdd94c3febe83598a2d6c0b4dc0

    【讨论】:

      【解决方案2】:

      你可以使用函数DECODE():

      ORDER BY DECODE(pType, 1, A, 2, B, 3, C),
               DECODE(pType, 1, B, 2, C, 3, A),
               DECODE(pType, 1, C, 2, D, 3, B),
               DECODE(pType, 1, D, 2, A, 3, D)  
      

      【讨论】:

        猜你喜欢
        • 2021-12-13
        • 2014-11-20
        • 2017-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        • 1970-01-01
        相关资源
        最近更新 更多