[英]SQL Else If statement to return text value from numeric value of another column - not working
I need to have a calculated column Site_Condition
that will return a text value based on the numeric value of another column Condition_Score
which is in the same table. 我需要具有一个计算所得的列
Site_Condition
,该列将基于同一表中另一列Condition_Score
的数值返回一个文本值。
Below is what I have tried inserting into the Computed Column Specification, I but get this message: 以下是我尝试插入“计算列规范”中的内容,但收到此消息:
Error validating the formula
验证公式时出错
I have also tried creating it from script "Create table as" using same syntax below ie: Site_Condition AS (IF....) 我还尝试过使用下面的相同语法从脚本“创建表为”创建它,即:Site_Condition AS(IF ....)
What am I doing wrong? 我究竟做错了什么?
IF([Condition_Score]<0.51,'Very poor',(ELSE
IF([Condition_Score]<1.51,'Poor', ELSE
IF([Condition_Score]<2.51,'Moderate',ELSE
IF([Condition_Score]<3.51,'Good',ELSE
IF([Condition_Score]>3.51,'Excellent'))))))
In SQL, we use CASE
rather than IF
在SQL中,我们使用
CASE
而不是IF
CASE WHEN [Condition_Score]<0.51 THEN 'Very poor'
WHEN [Condition_Score]<1.51 THEN 'Poor'
WHEN [Condition_Score]<2.51 THEN 'Moderate'
WHEN [Condition_Score]<3.51 THEN 'Good'
ELSE 'Excellent' END
But for completeness, here's the IIF()
version (note the extra " I
", short for "Immediate If"): 但是为了完整
IIF()
,这是IIF()
版本(请注意额外的“ I
”,“ Immediate If”的缩写):
IIF([Condition_Score]<0.51, 'Very poor',
IIF([Condition_Score]<1.51, 'Poor',
IIF([Condition_Score]<2.51, 'Moderate',
IIF([Condition_Score]<3.51,'Good',
'Excellent'))))
If I recall correctly, IIF()
is not available until Sql Server 2016. 如果我没记错的话,直到Sql Server 2016
IIF()
才可用。
These also fix a bug whereby if the score was exactly 3.51 the result would be NULL
. 这些还修复了一个错误,即如果分数恰好是 3.51,则结果将为
NULL
。
This is Simple way to ...perform your Query... 这是执行查询的简单方法。
DECLARE @Condition_Score AS DECIMAL
SET @Condition_Score=1.25
DECLARE @Message AS VARCHAR(50)
IF(@Condition_Score<0.51)
BEGIN
SET @Message ='Very poor'
END
else IF(@Condition_Score<1.51)
BEGIN
SET @Message ='poor'
END
ELSE IF(@Condition_Score<2.51)
BEGIN
SET @Message ='Moderate'
END
ELSE IF (@Condition_Score<3.51)
BEGIN
SET @Message ='Good'
END
ELSE IF(@Condition_Score>3.51)
BEGIN
SET @Message='Excellent'
END
PRINT @Message
Note:-Here " PRINT @Message" for Checking the Current Output 注意:-这里“ PRINT @Message”用于检查当前输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.