选择子查询避免多次运行?

时间:2013-07-11 01:21:52

标签: sql sql-server

我有这样的查询

Select 
     Col_A
    ,Col_B
    ,Col_C
    ,CASE 
        WHEN (SELECT ...{a very complicated query}...) IS NOT NULL THEN 1
        ELSE 0
     END CASE AS Col_D
FROM
    MyTable

生成Col_D的子查询在非空时返回一个整数。

我需要显示Col_D的BIT,但我还需要显示它返回的INT。通常,我只是重写子查询并将其称为Col_E,但考虑到它的复杂性,我真的不想运行它两次。理想情况下,我会:

Select
     Col_A
    ,Col_B
    ,Col_C
    ,(SELECT ...{a very complicated query}...) AS Col_E
    ,CASE 
        WHEN Col_E IS NOT NULL THEN 1
        ELSE 0
     END CASE AS Col_D
FROM
    MyTable

我有任何选择吗? (MS SQL 2008)

编辑: 对不起 - 我应该提到复杂的查询包含基于我的列的where子句,即

SELECT ...{a very complicated query}... WHERE X = Col_A AND Y = Col_B

2 个答案:

答案 0 :(得分:3)

因此,如果查询结果只是单个值或null,则可以使用:

Select 
     Col_A
    ,Col_B
    ,Col_C
    ,CASE 
        WHEN t.whatevercol IS NOT NULL THEN 1
        ELSE 0
     END CASE AS Col_D,
    t.whatevercol
FROM
    MyTable, (SELECT ...{a very complicated query}...) t

要小心,因为这可能导致笛卡尔积,但是如果有可能的多次回报。如果有可以加入的字段,那可能是一种更好的方法(因为你要检查NULL,你可能需要一个OUTER JOIN)。

答案 1 :(得分:2)

您可以在另一个Col_E中嵌套返回SELECT的查询,并在其上添加Col_D,如下所示:

SELECT 
     Col_A
    ,Col_B
    ,Col_C
    ,Col_E
    , CASE 
        WHEN Col_E IS NOT NULL THEN 1
        ELSE 0
     END CASE AS Col_D
FROM (
    Select
         Col_A
        ,Col_B
        ,Col_C
        ,(SELECT ...{a very complicated query}...) AS Col_E
    FROM
        MyTable
) X

这样您就不需要复制查询,因为其结果可供外SELECT使用。