SQLServerの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