SQL Query中的复杂排序:可能使用CASE WHEN

时间:2010-09-10 11:10:03

标签: sql oracle sql-order-by

我有一个复杂的优先级算法,我希望在返回优先级数据页时用SQL编写。

根据固定值对其中一些进行优先级排序,其他按变量值排序。即。

// Initial sort on ATTR1 (value1/value2 is higher than value3)
if ATTR1 = value1 or value2
  then orderBy creationDate, then modifiedDate, then author
else if ATTR1 = value3
  then 
    // if ATTR1 = value3, do secondary sort on ATTR2 (value4 is higher than value5)
    if ATTR2 = value4
       then orderBy oldPriority, then modifiedDate, then creationDate, then author
    if ATTR2 = value5
       then orderBy creationDate, then modifiedDate

我已经看过SQL CASE WHEN,但不知道如何使用第二级属性比较来实现这一点。

CASE WHEN是否是实现这一目标的合适工具?有没有人有关于处理额外复杂程度的任何提示?

提前谢谢!

2 个答案:

答案 0 :(得分:4)

这样的事情应该这样做:

ORDER BY attr1,
CASE WHEN ATTR1 IN (value1, value2)
       THEN TO_CHAR(creationDate,'YYYYMMDDHH24MISS') 
            || to_char(modifiedDate,'YYYYMMDDHH24MISS') || author
     WHEN ATTR1 = value3
       THEN attr2 || CASE WHEN ATTR2 = value4
                            THEN to_char(oldPriority,'99999')
                                 || to_char(modifiedDate,'YYYYMMDDHH24MISS')
                                 || to_char(creationDate,'YYYYMMDDHH24MISS') 
                                 || author
                          WHEN ATTR2 = value5
                            THEN to_char(creationDate,'YYYYMMDDHH24MISS')
                                 || to_char(modifiedDate,'YYYYMMDDHH24MISS')
                          END
     END

我认为oldPriority是一个NUMBER列,可能不是这样。重点是使用适当的格式掩码将所有内容转换为正确排序的字符串。

答案 1 :(得分:0)

做一些小的假设,似乎这应该有效:

order by
   case ATTR1
      when value1 then
         1
      when value2 then
         2
      when value3 then
         3
   end,
      when ATTR1 in (value1,value2) 
           or (ATTR1 = value3 and ATTR2 = value5) then
         creationDate
      else
         null
      end,
   case 
      when ATTR1 = value3 and ATTR2 = value4 then
         oldPriority
      else
         null
      end,
   modifiedDate,
   case
      when not (ATTR1 = value3 and ATTR2 = value5) then
          author
      else null
      end