具有OR条件的案例表达

时间:2017-10-18 19:12:50

标签: sql oracle

我有以下Case表达式,可以产生正确的结果。当我添加“OR”条件时,结果会发生变化。

  1. 为什么结果随着“OR”的增加而改变?

    我希望通过添加“OR”语句ID 1仍应为“未分配”

  2. Or声明

    --OR ( TABLEA.ROLE != 'RED' AND  CCP.STATUS = 'Active' 
      --AND  TO_CHAR(CCP.END_DATE,'MM/DD/YYYY') = '09/09/9000' 
    

    完整查询

    SELECT
      CASE 
        WHEN MAX(CASE WHEN TABLEA.ROLE = 'RED'
                            AND TABLEA.ID IS NULL
                            AND CCP.STATUS = 'Active')
                            --OR (TABLEA.ROLE != 'RED' AND  CCP.STATUS = 'Active'
                                  --AND TO_CHAR(CCP.END_DATE,'MM/DD/YYYY') = '09/09/9000')
                       THEN TABLEA.DT
                  END
              ) KEEP (DENSE_RANK LAST ORDER BY TABLEA.HISTORYID DESC,
                      CASE WHEN TABLEA.ROLE = 'RED'
                           THEN TABLEA.DT
                      END ASC NULLS FIRST
                     ) OVER (PARTITION BY CCP.ID) IS NULL
          THEN 'Unassigned'
        --WHEN TABLEA.ROLE != 'RED' THEN 'Unassigned'
        WHEN TO_CHAR(CCP.END_DATE,'MM/DD/YYYY') != '09/09/9000'
             AND CCP.STATUS = 'Closed'
          THEN 'Closed'
        ELSE 'Assigned'
      END AS CURRENT_STATUS2
      FROM TABLEA
    

    没有OR声明的结果:

     ID    CURRENT_STATUS2
     1       Unassigned   
    

    OR语句的结果:应该是未分配且未分配

     ID    CURRENT_STATUS2
     1       Assigned 
    

2 个答案:

答案 0 :(得分:1)

记住订单(来自上面的评论)这个和那个或那个不同于(this和that)或(this)

查询应为:

CASE 
WHEN MAX(CASE WHEN (TABLEA.ROLE = 'RED' 
  AND TABLEA.ID IS NULL 
  AND CCP.STATUS = 'Active' )
  OR( HIST.ROLE != 'RED' AND  CCP.STATUS = 'Active' 
  AND TO_CHAR(CCP.END_DATE,'MM/DD/YYYY') = '01/01/3000' )

答案 1 :(得分:0)

不容易阅读的代码。我想你只是几个方括号:

WHEN (TABLEA.ROLE = 'RED' 
AND TABLEA.ID IS NULL 
AND CCP.STATUS = 'Active')
OR ( TABLEA.ROLE != 'RED' AND  CCP.STATUS = 'Active' 
AND  TO_CHAR(CCP.END_DATE,'MM/DD/YYYY') = '09/09/9000')