简体   繁体   中英

CASE Statement with conditions

There are two fields in my table cust_shipmentdate_awb and comp_shipdate_awb. Iam trying to write a CASE Statement which should check both fields cust_shipmentdate_awb and comp_shipdate_awb is null or empty. If both are Null then show the result as 'Pending'. If any one field is not empty, then it should show as 'Completed' AND if both fields are entered also it should as 'Completed'. I have tried the below CASE statement. But its showing pending when both the fields data is entered.

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

Use a subquery.

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

You need to put your query inside a subquery then refer to that shipment_date field outside of that subquery like below:

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

You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.

Problem with alias

This should work

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

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