简体   繁体   中英

HOW to structure SQL CASE STATEMENT with multiple conditions

I would like to convert the below logic into a SQL query, and i know that it can be acheived using a CASE WHEN THEN ELSE statement , but i am not sure how i can put it together in the query. Please help.

  1. Where AG_AGENTS.SALES_AREA_DESC = Dom. - NAT
  2. If PX_PAXWEB.COUNTRY = AUT then PX_PAXWEB.POSTCODE
  3. If PX_PAXWEB.COUNTRY <> AUT then vwPxPaxweb.SALES_AREA
  4. If point 2 and/or 3 is null then just use AG_AGENTS.SALES_AREA_DESC
  5. Where AG_AGENTS.SALES_AREA_DESC = Int. – Inbound, then vwPxPaxweb.SALES_AREA
  6. If point 5 is null then use AG_AGENTS.SALES_AREA_DESC

      The new field can be called as SALES_AREA_DESC_2 

The general logic is:

select 
    CASE WHEN test1 = 'a' THEN 1
        WHEN test1 = 'b' THEN 2
        WHEN (test1 = 'c') AND (test2 is null) THEN 3
        ELSE 0 END as myfield
from mytable

In your case, if I understand your query correctly it is:

CASE WHEN (AG_AGENTS.SALES_AREA_DESC = Dom. - NAT) 
        AND (ISNULL(PX_PAXWEB.COUNTRY,'') = AUT) THEN PX_PAXWEB.POSTCODE
     WHEN (AG_AGENTS.SALES_AREA_DESC = Dom. - NAT) 
        AND (ISNULL(PX_PAXWEB.COUNTRY,'') <> AUT) THEN vwPxPaxweb.SALES_AREA
     WHEN (AG_AGENTS.SALES_AREA_DESC = Dom. - NAT) 
             AND (PX_PAXWEB.COUNTRY is null) THEN AG_AGENTS.SALES_AREA_DESC
     WHEN (AG_AGENTS.SALES_AREA_DESC = Int. – Inbound) 
        THEN vwPxPaxweb.SALES_AREA
     WHEN (AG_AGENTS.SALES_AREA_DESC = Int. – Inbound) 
        THEN AG_AGENTS.SALES_AREA_DESC
     WHEN (AG_AGENTS.SALES_AREA_DESC is null)
            OR (Int. is null) OR (Inbound is null) 
        THEN AG_AGENTS.SALES_AREA_DESC
     ELSE AG_AGENTS.SALES_AREA_DESC -- or some other exit value

END as SALES_AREA_DESC_2

Note: a few thing are not clear from your questions so I had to make assumptions: - Assumed "Dom.", "NAT", etc are fields (bit odd w the dot..) - I'm not sure which fields can be NULL (re: "If point 2 and/or 3 is null ", etc), so I picked all for the last branch of the case. So you can figure out the rest.

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