Coalesce
當欄位包含 NULL 值時,coalesce() 函式能用來指定預設或備用值。
coalesce() 會依序檢查引數,並回傳第一個非 NULL 的值(若存在)。
coalesce(NULL, 1, 2)= 1coalesce(NULL, NULL)=NULLcoalesce(2, 3, NULL)= 2
在 fortune500 資料中,industry 含有一些遺漏值。當 industry 為 NULL 時,請用 coalesce() 以 sector 的值作為 industry。接著找出最常見的產業。
本練習屬於課程
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
___ ___;