我们可以将CASE表达式/案例结果作为oracle中的连接表名称

时间:2015-07-23 13:05:24

标签: sql oracle

我有3个表说Employee,Permanent_Emp和Contract_Emp

SELECT E.EMP_NO,
   E.NAME,
   JET.EMP_TYPE,
   JET.DATE_JOINED
FROM Employee E
   LEFT OUTER JOIN              
   /* Here Join Table Name(JET) it can be Permanent_Emp or Contract_Emp 
      which i want as a result of my case expression. */
   ON (some condition here) ORDER BY E.EMP_NO DESC 

案例表达:

CASE
   WHEN (E.EMP_TYPE_CODE >10 )
        THEN
          Permanent_Emp  JET 
        ELSE
          Contract_Emp  JET
   END 

注意:表名和列名仅用于了解需求的示例。

如何从案例表达式中连接表名?

4 个答案:

答案 0 :(得分:2)

像这样的东西(虽然没有对你的表的描述,确切的连接条件或任何样本数据很难给出更准确的答案):

SELECT E.EMP_NO,
       E.NAME,
       COALESCE( P.EMP_TYPE, C.EMP_TYPE ) AS EMP_TYPE
       COALESCE( P.DATE_JOINED, C.DATE_JOINED ) AS DATE_JOINED
FROM   Employee E
       LEFT OUTER JOIN
       Permanent_Emp P
       ON ( E.EMP_TYPE_CODE > 10 AND E.EMP_NO = P.EMP_NO )
       LEFT OUTER JOIN
       Contract_Emp C
       ON ( E.EMP_TYPE_CODE <= 10 AND E.EMP_NO = C.EMP_NO )
ORDER BY
       E.EMP_NO DESC

答案 1 :(得分:1)

在select和join两个表中使用你的案例

作为

SELECT case when 1 then a.column
            when 2 then b.column
       end
from table c
join table a
on 1=1
join table2 b
on 1=1

但加入时你无法使用案例。最好是根据您的要求加入两个表和select条件语句

答案 2 :(得分:1)

无法在静态SQL中有条件地将表添加到查询中。如果Permanent_EmpContract_Emp中的相关列大致相同,则可以在子查询中使用union

SELECT *
FROM   employee e
       JOIN
       (SELECT employee_id, relevant_column, 'P' AS source_indicator
        FROM   permanent_emp
        UNION ALL
        SELECT employee_id, relevant_column, 'C' AS source_indicator
        FROM   contract_emp) se
          ON     e.employee_id = se.employee_id
             AND (   (e.emp_type_code >  10 AND source_indicator = 'P')
                  OR (e.emp_type_code <= 10 AND source_indicator = 'C'))

答案 3 :(得分:0)

使用Alan的查询作为起点,你仍然可以使用case语句,只需将其移动到连接条件:

 SELECT *
   FROM employee e
   JOIN (
         SELECT employee_id
              , relevant_column
              , 'P' AS source_indicator
           FROM permanent_emp
         UNION ALL
         SELECT employee_id
              , relevant_column
              , 'C' AS source_indicator
           FROM contract_emp
      ) se
     ON se.employee_id   = e.employee_id
    and se.source_indicator = case when e.emp_type_code > 10
                                   then 'P'
                                   else 'C'
                              end

此查询与Allan之间的唯一区别是使用case语句而不是or语句。