Coalesce
当某列包含 NULL 值时,coalesce() 函数可用于指定一个默认或后备值。
coalesce() 按顺序检查参数,并返回第一个非 NULL 的值(如果存在)。
coalesce(NULL, 1, 2)= 1coalesce(NULL, NULL)=NULLcoalesce(2, 3, NULL)= 2
在 fortune500 数据中,industry 包含一些缺失值。请使用 coalesce(),当 industry 为 NULL 时,用 sector 的值作为行业。然后找出最常见的行业。
本练习是课程的一部分
SQL 中的探索性数据分析
练习说明
- 使用
coalesce()从industry、sector或'Unknown'中选择第一个非NULL的值作为后备值。 - 将对
coalesce()的调用结果起别名为industry2。 - 统计每个
industry2值对应的行数。 - 找到最常见的
industry2值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
-- Use coalesce
SELECT ___(___, ___, 'Unknown') AS industry2,
-- Don't forget to count!
___
FROM ___
-- Group by what? (What are you counting by?)
GROUP BY ___
-- Order results to see most common first
___ ___ ___ ___
-- Limit results to get just the one value you want
___ ___;