Reputation: 261
I'm interested in making a case statement that pulls values from two different columns, one of which having a calculation involved.. I'm not sure how to make this work but I'll show you what I have so far. (I have one column that shows Item Type for example Special Order items, Discontinued Items and Items that are normally stocked. And the Second column shows the Quantity on Hand - Quantity on Sales Orders to determine if the item is in stock.) Here is my query
SELECT ItemID, ItemType, (QuantityOnHand - QuantityonSalesOrders) AS Instock
CASE
WHEN ItemType = 'SP / OR' THEN 'Special Order'
WHEN Instock < '1' THEN 'Out of Stock'
WHEN Instock > '0' THEN 'In Stock'
AS "Stock" FROM peachtree;
Upvotes: 6
Views: 21268
Reputation: 247720
For this type of request you will either have to reuse the calculation or use a subquery. This is because the alias that you are giving the Instock
value is not available for use within the select list:
SELECT ItemID,
ItemType,
Instock,
CASE
WHEN ItemType = 'SP / OR' THEN 'Special Order'
WHEN Instock < '1' THEN 'Out of Stock'
WHEN Instock > '0' THEN 'In Stock'
END AS "Stock"
FROM
(
select ItemID, ItemType, (QuantityOnHand - QuantityonSalesOrders) AS Instock
from peachtree
) p;
Or:
SELECT ItemID,
ItemType,
(QuantityOnHand - QuantityonSalesOrders) as Instock,
CASE
WHEN ItemType = 'SP / OR' THEN 'Special Order'
WHEN (QuantityOnHand - QuantityonSalesOrders) < '1' THEN 'Out of Stock'
WHEN (QuantityOnHand - QuantityonSalesOrders) > '0' THEN 'In Stock'
END AS "Stock"
FROM peachtree
Upvotes: 9