简体   繁体   中英

SQL Conditional AND

I want to determine the AND clause based on the value of the current row. So for example, my job table has 4 date columns: offer_date, accepted_date, start_date, reported_date. I want to check against an exchange rate based on the date. I know the reported_date is never null, but it's my last resort, so I have a priority order for which to join against the exchange_rate table. I'm not quite sure how to do this with a CASE statement, if that's even the right approach.

SELECT * FROM job j
INNER JOIN exchange_rate er ON j.currency_id = er.currency_id AND er.date =
(
  -- use offer_date if not null
  -- use accepted_date if above is null
  -- use start_date if above two are null
  -- use reported_date if above three are null
)

Should just be a simple coalesce, so something like:

SELECT      * 

FROM        job j

INNER JOIN  exchange_rate er 
    ON      j.currency_id = er.currency_id 
    AND     er.date = COALESCE( offer_date, accepted_date, start_date, reported_date )

CASE statement in a where clause.

CASE WHEN offer_date is not null THEN offer_date
     WHEN accepted_date IS NOT NULL THEN accepted_date 
     WHEN start_date  IS NOT NULL THEN start_date
     WHEN reported_date  IS NOT NULL THEN reported_date 
     ELSE '' END

it will work as per your require condition

One way is a case statement:

SELECT * FROM job j
INNER JOIN exchange_rate er
        ON j.currency_id = er.currency_id
       AND er.date =
case when j.offer_date is not null then j.offer_date
     when j.offer_date is null and j.accepted_date is not null then j.accepted_date
     when j.offer_date is null and j.accepted_Date is null and j.start_date is not null then j.start_date
     else j.reported_date
     end

You can use a CASE statement in a WHERE clause. I have used something them like:

field1 = CASE WHEN field2 IS NOT NULL field2 ELSE field1 END

So when you hit the else clause the AND is optional. Does that make sense?

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