SQL 案例语句 NULL 列
SQL Case Statement NULL column
proc SQL;
CREATE TABLE DATA.DUMMY AS
SELECT *,
CASE
WHEN (Discount IS NOT NULL)
THEN (Total_Retail_Price - (Total_Retail_Price * Discount)) * Quantity AS Rev
ELSE (Total_Retail_Price * Quantity) AS Rev
END
FROM DATA.Cumulative_Profit_2013 AS P
;
我正在尝试将可能为 NULL 的列作为 Revenue 表达式的一部分。但是我的案例陈述引发了问题。我检查了其他示例,但我不明白为什么这会有所帮助
在不了解 SAS 的情况下,正常的 SQL 语法为:
SELECT *,
CASE
WHEN (Discount IS NOT NULL)
THEN (Total_Retail_Price - (Total_Retail_Price * Discount)) * Quantity
ELSE (Total_Retail_Price * Quantity)
END AS Rev
即在case表达式结束后加上列别名。
看起来您可以使用 COALESCE
来实现您的目标,而无需明确的条件:
SELECT *,
(Total_Retail_Price - (Total_Retail_Price * COALESCE(Discount, 0))) * Quantity AS Rev
FROM DATA.Cumulative_Profit_2013 AS P
作为注释,我会这样写:
SELECT p.*,
(Total_Retail_Price * (1 - COALESCE(Discount, 0)) * Quantity) AS Rev
FROM DATA.Cumulative_Profit_2013 AP
我发现原始表达式中 Total_Retail_Price
的重复更难理解。
注意:所有答案都适用于 SAS。
proc SQL;
CREATE TABLE DATA.DUMMY AS
SELECT *,
CASE
WHEN (Discount IS NOT NULL)
THEN (Total_Retail_Price - (Total_Retail_Price * Discount)) * Quantity AS Rev
ELSE (Total_Retail_Price * Quantity) AS Rev
END
FROM DATA.Cumulative_Profit_2013 AS P
;
我正在尝试将可能为 NULL 的列作为 Revenue 表达式的一部分。但是我的案例陈述引发了问题。我检查了其他示例,但我不明白为什么这会有所帮助
在不了解 SAS 的情况下,正常的 SQL 语法为:
SELECT *,
CASE
WHEN (Discount IS NOT NULL)
THEN (Total_Retail_Price - (Total_Retail_Price * Discount)) * Quantity
ELSE (Total_Retail_Price * Quantity)
END AS Rev
即在case表达式结束后加上列别名。
看起来您可以使用 COALESCE
来实现您的目标,而无需明确的条件:
SELECT *,
(Total_Retail_Price - (Total_Retail_Price * COALESCE(Discount, 0))) * Quantity AS Rev
FROM DATA.Cumulative_Profit_2013 AS P
作为注释,我会这样写:
SELECT p.*,
(Total_Retail_Price * (1 - COALESCE(Discount, 0)) * Quantity) AS Rev
FROM DATA.Cumulative_Profit_2013 AP
我发现原始表达式中 Total_Retail_Price
的重复更难理解。
注意:所有答案都适用于 SAS。