简体   繁体   English

Oracle动态DESC和ASC按顺序排列

[英]Oracle dynamic DESC and ASC in order by

Order by is dynamic but the sort order is static. Order by是动态的,但排序顺序是静态的。

SELECT ...
Order By CASE WHEN InputParam = 'PRICE' THEN OFFER_PRICE END DESC,
         CASE WHEN InputParam = 'ENDING SOON' THEN EXPIRY_DATE END DESC, 
         CASE WHEN InputParam = 'DISCOUNT' THEN DISC_PERCENTAGE END DESC,
         CASE WHEN InputParam = 'SAVING' THEN SAVING END DESC

Now I need to make sure that the sort order is also dynamic. 现在我需要确保排序顺序也是动态的。 Is there some way to make sort order dynamic in the above query? 有没有办法在上面的查询中使排序顺序动态化?

If you also want to make the sort order (ASC/DESC) dynamic, you could do the following: 如果您还想使排序顺序(ASC / DESC)动态化,则可以执行以下操作:

SELECT ...
Order By CASE WHEN InputParam = 'PRICE' THEN l_so * OFFER_PRICE END,
         CASE WHEN InputParam = 'ENDING SOON' 
              THEN l_so * (SYSDATE - EXPIRY_DATE) END, 
         CASE WHEN InputParam = 'DISCOUNT' THEN l_so * DISC_PERCENTAGE END,
         CASE WHEN InputParam = 'SAVING' THEN l_so * SAVING END

with a variable l_so that contains 1 or -1 depending upon which sort order you want. 使用包含1或-1的变量l_so ,具体取决于您想要的排序顺序。

This works for me: 这对我有用:

order by 
  case when :dir_param = 'ASC' then
    case :col_param 
      when 'col_1_identifier' then col_1_name
      when 'col_2_identifier' then col_2_name
      ...
    end
  end,
  case when :dir_param = 'DSC' then
    case :col_param 
      when 'col_1_identifier' then col_1_name
      when 'col_2_identifier' then col_2_name
      ...
    end
  end desc

or 要么

order by 
case when :dir_param = 'ASC' and :col_param = 'col_1_identifier' then col_1_name end,
case when :dir_param = 'DSC' and :col_param = 'col_1_identifier' then col_1_name end desc,
case when :dir_param = 'ASC' and :col_param = 'col_2_identifier' then col_2_name end,
case when :dir_param = 'DSC' and :col_param = 'col_2_identifier' then col_2_name end desc

replace literals, variable and column names with those specific to your situation. 将文字,变量和列名称替换为您的具体情况。 Oracle seemed to be very picky about the placement of the desc sort direction qualifier. Oracle似乎对desc排序方向限定符的位置非常挑剔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM