带有条件CASE语句的SQL LEFT JOIN

时间:2015-10-13 13:48:35

标签: sql sql-server tsql join case

希望这是一个快速的

SELECT *
FROM T
left JOIN J ON 
  CASE
    WHEN condition1 THEN 1 --prefer this option even if CASE2 has a value
    WHEN condition2 THEN 2
    ELSE 0
  END = 1 (edit: but if 1 does not satisfy, then join on 2)

两种情况都返回结果,但我希望那么1取代那么2并成为查找优先级

我可以让SQL执行max(CASE)上的加入吗?

基本上我试图从Excel复制嵌套的INDEX / MATCH

编辑:我听到的是Case应该在第一次返回TRUE时停止,但是当我测试时它不会像那样

SELECT *
FROM T
left JOIN J ON 
  CASE
    WHEN condition1 THEN 1 --prefer this option even if CASE2 has a value
    WHEN condition2 THEN 1
    ELSE 0
  END = 1

它似乎有时更喜欢第二个THEN 1,但并不总是......是否有任何我想念的东西会导致这种行为?

4 个答案:

答案 0 :(得分:2)

哪个条件导致行在连接中匹配并不重要。在合并中使用case表达式是有正当理由的,但我认为您只想or条件,然后使用case表达式输出匹配的排名原因。< / p>

SELECT *, CASE WHEN <condition1> THEN 1 WHEN <condition2> THEN 2 END as match_code
FROM T LEFT OUTER JOIN J ON <condition1> or <condition2>

我不知道对于&#34;嵌套的INDEX / MATCH&#34;来自Excel。如果我在上面的错误轨道上,那么您是否正在寻找嵌套的案例表达式?

现在,如果您的条件会在不同的行之间匹配,而您只想保留一个...

WITH matches AS (
    SELECT *, CASE WHEN <condition1> THEN 1 WHEN <condition2> THEN 2 END AS match_code
    FROM T LEFT OUTER JOIN J ON <condition1> OR <condition2>
), ranked as (
    SELECT *, MIN(match_code) OVER (PARTITION BY ???) AS keeper
    FROM matches
)
SELECT ...
FROM ranked
WHERE match_code = keeper

答案 1 :(得分:0)

嗯,您的CASE语句中总是有几个条件:

  SELECT *
FROM T

left JOIN J ON 
  CASE
    WHEN condition1 THEN 1 --prefer this option even if CASE2 has a value
    WHEN condition2 And !condition1 THEN 2
  ELSE 0
END = 1

- UPDATED-- 如果您的两个条件都需要匹配,但condition1是可选的,那么您也可以尝试这个语句:

  SELECT *
FROM T  
left JOIN J ON 
  CASE
    WHEN condition1 And condition2 THEN 1 --Both conditions match
    WHEN condition2 THEN 2 -- condition1 has no match
  ELSE 0
END = 1

答案 2 :(得分:0)

您可以分两步使用With语句:

 With first_join as  
    (SELECT *
    FROM T
    left JOIN J ON condition1)
      select * from first_join 
    join J On case when Name_of_2nd_condition is null 
       then     condition2 
      ELSE null end

答案 3 :(得分:0)

您可以使用CROSS APPLY / OUTER APPLY运算符:https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/

SELECT *
FROM T
    OUTER APPLY (SELECT TOP 1 *
                 FROM J
                 WHERE condition1 OR condition2
                 ORDER BY order) J