排序依据是动态的,但排序顺序是静态的。
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
现在我需要确保排序顺序也是动态的。有没有办法在上面的查询中使排序顺序动态化?
答案 0 :(得分:16)
如果您还想使排序顺序(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
变量l_so
包含1或-1,具体取决于您想要的排序顺序。
答案 1 :(得分:9)
这对我有用:
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
或
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
将文字,变量和列名称替换为您的具体情况。对于desc排序方向限定符的放置,Oracle似乎非常挑剔。