Oracle SQL自定义与联盟排序

时间:2014-01-29 15:38:15

标签: sql oracle case union

我有两个表正在联合并希望使用ORDER BY CASE自定义订单,但我一直在使用ORA-01785:ORDER BY项必须是SELECT-list表达式错误的编号。

我的2个表每个都有一个名为“VISIT”的列,包含(类似于)以下数据:

FollowUp表:BASELINE,1_MONTH,2_MONTH

程序表:PROCEDURE

我希望将这些表联合起来并按以下顺序排序:BASELINE,PROCEDURE,1_MONTH,2_MONTH

以下是我认为应该有效的方法:

SELECT VISIT
FROM FollowUp
UNION
SELECT VISIT
FROM Procedure
ORDER BY
    CASE VISIT
    WHEN 'BASELINE' THEN 1
    WHEN 'PROCEDURE' THEN 2
    WHEN '1_MONTH' THEN 3
    WHEN '2_MONTH' THEN 4
    ELSE 5 END

但是我收到01785错误。我还尝试用CASE VISIT替换CASE 1并获得相同的错误。谢谢你的帮助!

3 个答案:

答案 0 :(得分:2)

尝试使用子查询执行此操作:

select visit
from ((SELECT VISIT
       FROM FollowUp
      ) union
      (SELECT VISIT
       FROM Procedure
      )
     ) t
ORDER BY
    CASE VISIT
    WHEN 'BASELINE' THEN 1
    WHEN 'PROCEDURE' THEN 2
    WHEN '1_MONTH' THEN 3
    WHEN '2_MONTH' THEN 4
    ELSE 5 END;

如果您不需要重复删除,请使用union all

答案 1 :(得分:2)

试试这个:

  SELECT x.visit,
         CASE x.VISIT
            WHEN 'BASELINE' THEN 1
            WHEN 'PROCEDURE' THEN 2
            WHEN '1_MONTH' THEN 3
            WHEN '2_MONTH' THEN 4
            ELSE 5
         END
            sort_by
    FROM (SELECT VISIT FROM FollowUp
          UNION ALL
          SELECT VISIT FROM Procedure) x
ORDER BY SORT_BY

答案 2 :(得分:0)

试试这个:

SELECT VISIT, CASE VISIT WHEN 'BASELINE' THEN 1 WHEN 'PROCEDURE' THEN 2 WHEN '1_MONTH' THEN 3 WHEN '2_MONTH' THEN 4 ELSE 5 END ORDERFIELD FROM FollowUp UNION SELECT VISIT, CASE VISIT WHEN 'BASELINE' THEN 1 WHEN 'PROCEDURE' THEN 2 WHEN '1_MONTH' THEN 3 WHEN '2_MONTH' THEN 4 ELSE 5 END ORDERFIELD FROM Procedure ORDER BY ORDERFIELD