简体   繁体   English

SQL中的嵌套IF语句

[英]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: 我正在尝试重新创建在SQL查询中的excel中使用的以下嵌套IF语句:

=IF(AE20="",0,IF(AH20="",IF(AG20="",IF(AF20="",IF(AE20="","",AE20),AF20),AG20),AH20)) = IF(AE20 = “”,0,IF(AH20 = “”,IF(Ag 2 O的= “”,IF(AF20 = “”,IF(AE20 = “”, “”,AE20),AF20),Ag 2 O的), 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. 我进行了一些研究,似乎需要使用CASE,但是在示例中,我仍然无法使用上述示例中的正确语法连接点。

I assumed it would start as 我以为它会开始为

Select Case When ex_table.AE = "" ex_table.AE =“”时选择大小写

and I'm not sure where to go from there. 而且我不确定从那里去哪里。 I appreciate your help! 我感谢您的帮助!

EDIT 编辑

mysql table is called best_estimate . mysql表称为best_estimate

i have the following fields: JCE_TOTAL, CDSI_TOTAL, INITIAL_TOTAL and FINAL_TOTAL . 我有以下字段: 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). 我希望我的SQL查询能够遍历这些列并选择最新的可用值(这些值随着时间的流逝而变得可用,按照上面列出的顺序)。

If there is a value in FINAL_TOTAL it should pick the value in FINAL_TOTAL. 如果FINAL_TOTAL中有一个值,则应选择FINAL_TOTAL中的值。

If FINAL_TOTAL is blank but there is a value in INITIAL_TOTAL, it should select that value. 如果FINAL_TOTAL为空白,但INITIAL_TOTAL中有一个值,则应选择该值。

If those two fields are both blank, but CDSI_TOTAL has a value, it should pick CDSI_TOTAL, etc. 如果这两个字段都为空,但CDSI_TOTAL有一个值,则应选择CDSI_TOTAL,依此类推。

If all the fields are blank, the result should be 0 如果所有字段均为空白,则结果应为0

If I got your goal correctly you don't need to do this mega nested CASE statment. 如果我正确地确定了您的目标,则无需执行此大型嵌套的CASE语句。 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

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

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