简体   繁体   中英

Mysql CASE statement multiple columns

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM