简体   繁体   English

Mysql CASE语句多列

[英]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: 这是因为您在提供Instock值的别名无法在选择列表中使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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