1

是否可以在 SQL Server case 语句中的 case 表达式的 when 表达式中进行布尔比较。我有一个 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
4

3 回答 3

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;
于 2012-07-18T13:50:17.813 回答
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
于 2012-07-18T13:52:06.567 回答
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
于 2012-07-18T13:50:58.803 回答