CASE THEN中的SQL Server子查询具有多个JOINS

时间:2017-06-09 06:10:40

标签: sql-server

我已经搜索过高低的答案,但我找不到答案......

我试图在基于限定符的CASE THEN语句中运行子查询,如下所示:

SELECT
    CASE
        WHEN cbpotm.DOLCheck LIKE '%<%'
        THEN
        (
            SELECT
                ...
            FROM #AnotherTempTable AS CB
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            WHERE CONDITION AND CONDITION
            AND CONDITION IN ( 1, 2, 3, 4 )
            AND CAST(SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 1, 4) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 5, 2) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 7, 2) AS DATE) BETWEEN CB.SomeDate AND CB.SomeOtherDate
            GROUP BY FIELD, FIELD
        )
        END
FROM    
#TempTable cbpotm

显然我错过了这个标记,因为我不允许在JOIN内有多个CASE THEN而没有引入带有EXISTS子句的语句。
我没有试图将声明与任何内容进行比较,因此我无法理解为什么我只应该使用单个字段来匹配? 我也不知道为什么我应该使用EXISTS,因为我没有尝试执行验证...

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT *
FROM    
#TempTable cbpotm
outer apply
(
            SELECT *
            FROM #AnotherTempTable AS CB
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            LEFT OUTER JOIN ...
            WHERE CONDITION AND CONDITION
            AND CONDITION IN ( 1, 2, 3, 4 )
            AND CAST(SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 1, 4) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 5, 2) + '-' + SUBSTRING(CAST(tflr.DateKey AS VARCHAR), 7, 2) AS DATE) BETWEEN CB.SomeDate AND CB.SomeOtherDate
            AND cbpotm.DOLCheck LIKE '%<%'
            GROUP BY FIELD, FIELD

) tmp