SQL Conditional JOIN column [duplicate]

拈花ヽ惹草 提交于 2019-12-06 08:54:14

问题


I want to determine the JOIN column 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.

INNER JOIN exchange_rate c1 ON c1.date = {{conditionally pick a column here}}

  -- use j.offer_date if not null
  -- use j.accepted_date if above is null
  -- use j.start_date if above two are null
  -- use j.reported_date if above three are null

回答1:


Try logic like this:

INNER JOIN
exchange_rate c1
ON c1.date = coalesce(j.offer_date, j.accepted_date, j.start_date, j.reported_date)

The coalesce() function returns the first non-NULL value in the list.




回答2:


The CASE statement could look something like this:

INNER JOIN exchange_rate c1 ON c1.date =
CASE
    WHEN j.offer_date IS NOT NULL THEN j.offer_date
    WHEN j.accepted_date IS NOT NULL THEN j.accepted_date
    WHEN j.start_date IS NOT NULL THEN j.start_date
    ELSE j.reported_date
END


来源:https://stackoverflow.com/questions/25255240/sql-conditional-join-column

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