遍历Case when子句中的其他表

时间:2018-10-02 12:26:38

标签: sql for-loop foreach case-when

我有以下CASE WHEN子句

SELECT T0.foo, CASE WHEN T0.Column1 = 'Y' THEN '8mm' 
            WHEN T0.Column2 = 'Y' THEN '10mm' 
            WHEN T0.Column7 = 'Y' THEN '13mm'
            WHEN T0.Column50 = 'Y' THEN '30mm' END AS 'Width'
            ...
FROM Table1 T0

实际上,映射是另一个查询Table2

的结果
=========================
   Column1      Column2
=========================
   Column1      8mm
   Column2      10mm
   Column7      13mm
   Column50     30mm 
   ...          ...

我正在寻找一种方法来生成第一条语句中的CASE WHEN子句,并通过第二条语句的结果对每个循环或迭代进行某种形式的构建。

伪代码:

SELECT T0.foo, CASE WHEN (Select Column1 FROM Table2) = 'Y' THEN (SELECT Column2 FROM Table2) as 'Width'
FROM Table1 T0

1 个答案:

答案 0 :(得分:0)

使用join

SELECT T1.foo, t2.Width
FROM Table1 T1 LEFT JOIN
     Table2 t2
     ON (t1.column1 = 'Y' AND t2.column = 'Column1') OR
        (t1.column1 = 'Y' AND t2.column = 'Column7') OR
        . . .