是否可以在 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