使用Computations的SQL Sub查询

时间:2011-09-16 23:45:53

标签: sql-server-2008

我有3个表Tablle1,Table2,Table3。 表1和表1表2与Id1相关。 表2&表3与Id2相关。

  1. 我有以下查询可行。我如何获得CTotal = C00 + C01 + C02?

  2. 我在哪里添加OUTPUT语句以返回STOTAL&的值。 CTOTAL?

  3. SELECT X.Id1, X.S00, X.S01, X.S02, X.S00 + X.S01 + X.S02 AS STOTAL,
           CEILING(X.S00 / @Size) AS C00, CEILING(X.S01 / @Size) AS C01, 
           CEILING(X.S02 / @Size) AS C02,
           Tble1.Select00, Table1.Select01, Table1.Select02
    
    FROM(
        SELECT Table1.Id1, 
            SUM(CASE WHEN Table1.Select00 = 1 THEN Table3.Num00 ELSE 0 END) AS S00, 
            SUM(CASE WHEN Table1.Select01 = 1 THEN Table3.Num01 ELSE 0 END) AS S01, 
            SUM(CASE WHEN Table1.Select02 = 1 THEN Table3.Num02 ELSE 0 END) AS S02
        FROM  Table1 INNER JOIN
                    Table2 ON Table1.Id1 = Table2.Id1 INNER JOIN
                Table3 ON Table2.Id2 = Table3.Id2
            WHERE  (Table1.Id1 = @Id1
        )
        GROUP BY Table1.Id1) AS X INNER JOIN  Table1  ON X.Id1 = Table1.Id1
    

2 个答案:

答案 0 :(得分:3)

您只需添加CEILING(X.S00 / @Size) + CEILING(X.S01 / @Size) + ... AS CTotal或使用派生表:

SELECT a.*, a.C01+a.C02+a.C03 AS CTotal FROM
(
    [your_old_query]
)a

派生表的另一种替代方法 - CTE(公用表表达式)

答案 1 :(得分:0)

用另外一个外部选择包装查询并将它们全部加在一起。