開始使用免費開始

Coalesce

當欄位包含 NULL 值時,coalesce() 函式能用來指定預設或備用值。

coalesce() 會依序檢查引數,並回傳第一個非 NULL 的值(若存在)。

  • coalesce(NULL, 1, 2) = 1
  • coalesce(NULL, NULL) = NULL
  • coalesce(2, 3, NULL) = 2

fortune500 資料中,industry 含有一些遺漏值。當 industryNULL 時,請用 coalesce()sector 的值作為 industry。接著找出最常見的產業。

本練習屬於課程

SQL 中的探索式資料分析

檢視課程

練習說明

  • 使用 coalesce()industrysector 或作為備援的 '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
 ___ ___;
編輯並執行程式碼