SQL Server 具有多个WHEN值的CASE命令的SQL语法

aelbi1ox  于 2023-02-11  发布在  其他
关注(0)|答案(1)|浏览(229)

TL/DR如果条件是CASE级别的,是否可以在"WHEN"之后使用"IN"语法?
我的场景:
我正在编写一个带有多个WHEN值验证的SQL CASE语句。CASE条件很复杂(而且很长),所以我不想在WHEN级别重复它。
这是可行的:

CASE
   WHEN ( SELECT VALUE FROM Tab1 INNER JOIN Tab2 ON Tab1 ....very long statement) IN ('A','B','C') THEN 1
   WHEN ( same very long statement as above) IN ('D','E','F') THEN 2
   WHEN ( same very long statement as above) IN ... etc
END

我想让它更易读,但是下面的语法失败了

CASE ( SELECT VALUE FROM Tab1 INNER JOIN Tab2 ON Tab1 ....very long statement) 
   WHEN IN ('A','B','C') THEN 1 -- fails syntax error
   WHEN 'D' OR 'E' OR 'F' THEN 2 -- also fails syntax error
END

当然,我试图避免列出所有的值与相同的结果在不同的时候,语法下面的工作,但非常长的值列表

CASE ( SELECT VALUE FROM Tab1 INNER JOIN Tab2 ON Tab1 ....very long statement) 
   WHEN 'A' THEN 1
   WHEN 'B' THEN 1
   WHEN 'C' THEN 1
   WHEN 'D' THEN 2
   WHEN 'E' THEN 2
   WHEN 'F' THEN 2
....
END

SQL在那里能为我做些什么?

fdbelqdn

fdbelqdn1#

按照您所做的那样制定长查询,并将其与主查询进行CROSS JOIN:

SELECT
  base_query.other
, base_query.columns
, base_query.otherquery
, CASE
    WHEN xcross.result IN ('A','B','C') THEN 1
    WHEN xcross.result IN ('D','E','F') THEN 2
    WHEN xcross.result IN ('G','H','I') THEN 3
    ELSE NULL
  END
FROM other_table ot
JOIN yet_other_table you on ot.join_col = yot.join_col
CROSS JOIN (
  SELECT val AS result FROM Tab1 INNER JOIN Tab2 ON Tab1 ....very long statement
) AS xcross

相关问题