简体   繁体   中英

Case Expression with OR condition

I have the below Case expression that produces the correct results. When I add my "OR" condition the results change.

  1. Why are results changing with the addition of "OR"?

    I would expect with the addition of the "OR" statement ID 1 should still be "Unassigned"

Or statement

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

Full query

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

Results without OR statement:

 ID    CURRENT_STATUS2
 1       Unassigned   

Results with OR statement: Should be Unassigned and not assigned

 ID    CURRENT_STATUS2
 1       Assigned 

Remembering the order (from comment above) this and that or this is different from (this and that) or (this)

Query should read:

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' )

Not easy code to read. I think you are just a couple brackets away:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM