基于临时列加入

时间:2017-08-16 14:21:51

标签: sql sql-server-2008 join temp

我有两个需要连接的表,但唯一相似的列有需要删除的多余数据。我只想修改表,但我只能读取它们。因此,我从表中删除不需要的文本并添加临时列,但我无法加入它。我收到错误:

  

无效的列名称'TempJoin'

SELECT
    CASE WHEN CHARINDEX('- ExtraText',a.Column1)>0 THEN LEFT(a.Column1, (CHARINDEX('- ExtraText', a.Column1))-1)
         WHEN CHARINDEX('- ExtraText',a.Column1)=0 THEN a.Column1
    END AS TempJoin
    ,a.Column1
    ,b.Column2
FROM Table1 as a 
LEFT JOIN Table2 as b WITH(NOLOCK) ON b.Column2=TempJoin

1 个答案:

答案 0 :(得分:6)

最简单的方法是将其包装在CTE中。另外,be careful using NOLOCK,除非您有明确的理由。

WITH cte AS (
    SELECT
        CASE WHEN CHARINDEX('- ExtraText',a.Column1) > 0
             THEN LEFT(a.Column1, (CHARINDEX('- ExtraText', a.Column1))-1)
             WHEN CHARINDEX('- ExtraText',a.Column1) = 0
             THEN a.Column1
        END AS TempJoin,
        a.Column1
    FROM Table1 AS a
)

SELECT *
FROM cte
LEFT JOIN Table2 AS b WITH(NOLOCK) ON b.Column2 = TempJoin;