SQL Server CASE语句的条件结果

时间:2012-07-18 13:46:45

标签: sql sql-server sql-server-2000

是否可以在SQL Server case语句中的case-expression上的when-expression中进行布尔比较。我有一个SELECT语句,其逻辑类似于以下内容:

SELECT T1.ProductNumber,
    CASE
        WHEN (SELECT SUM(T2.Quantity) FROM Table2 AS T2 WHERE T2.Product=T1.Product) IS NULL
            THEN T1.Quantity
        WHEN (SELECT SUM(T2.Quantity) FROM Table2 AS T2 WHERE T2.Product=T1.Product) > T1.Quantity
            THEN T1.Quantity
        ELSE T1.Quantity - (SELECT SUM(T2.Quantity) FROM Table2 AS T2 WHERE T2.Product=T1.Product)
    END
FROM Table1 AS T1

这似乎是Table2上的大量重复查找。如果可能的话,我想做这样的事情:

SELECT T1.ProductNumber,
    CASE (SELECT SUM(T2.Quantity) FROM Table2 AS T2 WHERE T2.Product=T1.Product) as altQty
        WHEN altQty IS NULL
            THEN T1.Quantity
        WHEN altQty > T1.Quantity
            THEN T1.Quantity
        ELSE T1.Quantity - altQty
    END
FROM Table1 AS T1

3 个答案:

答案 0 :(得分:4)

您不能以这种方式引用别名,但如果将其放在子查询/派生表中,则可以。

SELECT ProductNumber, CASE WHEN altQty IS NULL
            THEN Quantity
        WHEN altQty > Quantity
            THEN Quantity
        ELSE Quantity - altQty END
FROM 
(
  SELECT T1.ProductNumber, T1.Quantity, 
    altQty = (SELECT SUM(T2.Quantity) FROM Table2 AS T2 WHERE T2.Product=T1.Product)
  FROM Table1 AS T1
) AS x;

答案 1 :(得分:3)

SELECT T1.ProductNumber,
    CASE 
        WHEN T2.Qty IS NULL
            THEN T1.Quantity
        WHEN T2.Qty > T1.Quantity
            THEN T1.Quantity
        ELSE T1.Quantity - T2.Qty END
FROM Table1 AS T1
    LEFT JOIN (SELECT ProductNumber, SUM(Quantity) AS Qty FROM Table2 GROUP BY ProductNumber) AS T2
        ON T1.ProductNumber = T2.ProductNumber

答案 2 :(得分:1)

不,但您可以删除重复的查找。

SELECT ProductNumber,
       CASE WHEN T2Quantity IS NULL THEN T1Quantity
            WHEN T2Quantity > T1Quantity THEN T1Quantity
            ELSE T1Quantity - T2Quantity END
  FROM
   (SELECT T1.ProductNumber, T1.Quantity as T1Quantity, SUM(T2.Quantity) as T2Quantity
      FROM Table1 AS T1 LEFT OUTER JOIN 
           Table2 AS T2 ON T2.Product=T1.Product
     GROUP BY T1.ProductNumber) innerTbl