带有条件的CASE声明

时间:2016-09-01 05:20:22

标签: mysql if-statement case

我的表cust_shipmentdate_awb和comp_shipdate_awb中有两个字段。我试图写一个CASE语句,它应该检查两个字段cust_shipmentdate_awb和comp_shipdate_awb是null还是空。如果两者都为空,则将结果显示为“待定”。如果任何一个字段不为空,则它应显示为“已完成”。如果同时输入两个字段,则它应显示为“已完成”。我已经尝试过以下CASE声明。但是当输入两个字段数据时它显示为挂起。

    CASE    
When cust_shipmentdate_awb Is Null Or cust_shipmentdate_awb = '' Then 'Pending'   
Else 'Completed' End AS shipment_status

3 个答案:

答案 0 :(得分:1)

使用子查询。

SELECT CASE WHEN shipment_date Is Null Or shipment_date = '' 
            THEN 'Pending' 
            Else 'Completed' 
        End AS shipment_status
FROM (
    SELECT CASE 
            When commercial_logi_freight.cust_shipmentdate_awb Is Null Or 
commercial_logi_freight.cust_shipmentdate_awb = '' 
            Then commercial_logi_freight.comp_shipdate_awb
            Else commercial_logi_freight.cust_shipmentdate_awb 
        End AS shipment_date
    FROM ...) AS x

答案 1 :(得分:1)

您需要将查询放在子查询中,然后引用该子查询之外的shipment_date字段,如下所示:

SELECT 
subQuery.*,
Case When shipment_date Is Null Or shipment_date = '' Then 'Pending' Else 'Completed' End AS shipment_stat
FROM 
(
    #YOUR QUERY GOES HERE.....
    SELECT 
    CASE 
    When commercial_logi_freight.cust_shipmentdate_awb Is Null Or 
    commercial_logi_freight.cust_shipmentdate_awb = '' Then
     commercial_logi_freight.comp_shipdate_awb
            Else commercial_logi_freight.cust_shipmentdate_awb End AS shipment_date
    FROM your_table

) AS subQuery
  

您只能在GROUP BY,ORDER BY或HAVING中使用列别名   条款。

Problem with alias

答案 2 :(得分:0)

这应该有效

CASE 
 When commercial_logi_freight.cust_shipmentdate_awb Is Null Or commercial_logi_freight.cust_shipmentdate_awb = '' Then commercial_logi_freight.comp_shipdate_awb
 Else commercial_logi_freight.cust_shipmentdate_awb End AS shipment_date,
CASE 
 When commercial_logi_freight.cust_shipmentdate_awb Is Null Or commercial_logi_freight.cust_shipmentdate_awb = '' Then 'Pending'
 Else 'Completed' End AS shipment_status