開始使用免費開始

使用 CONVERT()

CONVERT() 函式可以協助你把日期轉成想要的格式。

你需要取得一份報表,內容包含機場、航空公司、取消航班數與註冊日期,而且註冊時間落在 2014 年前 6 個月。你發現 registration_date 欄位的格式是 yyyy-mm-dd,而你想用 CONVERT() 函式把結果顯示為 mm/dd/yyyy 格式,這個格式代碼為 101(硬性指定)。

請注意,registration_date 欄位的型別是 VARCHAR(10),而不是日期。

本練習屬於課程

在 SQL Server 資料庫中清理資料

檢視課程

練習說明

  • 先把 registration_date 欄位的型別轉為 DATE,並以 mm/dd/yyyy 格式輸出。
  • registration_date 欄位轉為 mm/dd/yyyy 格式,用來篩選結果。
  • mm/dd/yyyy 格式篩選 2014 年前 6 個月的結果。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

SELECT 
    airport_code,
    carrier_code,
    canceled,
    -- Convert the registration_date to a DATE and print it in mm/dd/yyyy format
    ___(VARCHAR(10), ___(registration_date AS DATE), 101) AS registration_date
FROM flight_statistics 
-- Convert the registration_date to mm/dd/yyyy format
WHERE ___(VARCHAR(10), ___(registration_date AS DATE), 101) 
	-- Filter the first six months of 2014 in mm/dd/yyyy format 
	BETWEEN '___' AND '___'
編輯並執行程式碼