縮短過長字串
evanston311 的 description 欄位可能非常長。你可以用 length() 函式取得字串長度。
為了顯示或快速瀏覽資料,你可能只想顯示前幾個字元。你可以使用 left() 函式,擷取每個值開頭指定數量的字元。
為了表示還有更多內容,請在被縮短的 description 結尾串接 '...'。要做到這點,你可以用 CASE WHEN 陳述式,僅在字串長度大於 50 時加入 '...'。
當 description 以「單字」 "I" 開頭時,選取 description 的前 50 個字元。
本練習屬於課程
SQL 中的探索式資料分析
練習說明
選取
description的前 50 個字元,並在description的length()大於 50 時於結尾串接'...'。否則就原樣選取description。只選取以「單字」 'I' 開頭,而非以「字母」 'I' 開頭的描述。
- 例如,你應該選取「"I like using SQL!"」,但不應選取「"In this course we use SQL!"」。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
-- Select the first 50 chars when length is greater than 50
SELECT CASE WHEN length(___) ___ ___
THEN ___(___, ___) || ___
-- otherwise just select description
ELSE description
END
FROM evanston311
-- limit to descriptions that start with the word I
WHERE ___ LIKE ___
ORDER BY description;