SQL Conditional AND

青春壹個敷衍的年華 提交于 2019-12-12 04:05:05

问题


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
)

回答1:


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 )



回答2:


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




回答3:


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



回答4:


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?



来源:https://stackoverflow.com/questions/25098188/sql-conditional-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!