简体   繁体   中英

Nested IF statement in SQL

I am trying to recreate the following nested IF statement that I am using in excel within a SQL query:

=IF(AE20="",0,IF(AH20="",IF(AG20="",IF(AF20="",IF(AE20="","",AE20),AF20),AG20),AH20))

I did some research, and it appears that I need to use CASE, but in the examples I've found I'm still not able to connect the dots on the proper syntax to use given the example above.

I assumed it would start as

Select Case When ex_table.AE = ""

and I'm not sure where to go from there. I appreciate your help!

EDIT

mysql table is called best_estimate .

i have the following fields: JCE_TOTAL, CDSI_TOTAL, INITIAL_TOTAL and FINAL_TOTAL .

I want my SQL Query to go through those columns and pick the most recent value available (the values become available over time, in the order listed above).

If there is a value in FINAL_TOTAL it should pick the value in FINAL_TOTAL.

If FINAL_TOTAL is blank but there is a value in INITIAL_TOTAL, it should select that value.

If those two fields are both blank, but CDSI_TOTAL has a value, it should pick CDSI_TOTAL, etc.

If all the fields are blank, the result should be 0

If I got your goal correctly you don't need to do this mega nested CASE statment. There is much simplier way:

SELECT COALESCE(AE, AH, AG, ...) AS my_value
FROM my_table

so according to yuor comment your query could be like:

SELECT COALESCE(FINAL_TOTAL, INITIAL_TOTAL, CDSI_TOTAL, JCE_TOTAL,  0 ) AS my_value
FROM best_estimate

EDIT

SELECT 
   OFS_ID,
   COALESCE(FINAL_TOTAL, INITIAL_TOTAL, CDSI_TOTAL, JCE_TOTAL,  0 ) AS my_value
FROM best_estimate

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