開始使用免費開始

由各部分組成日期

到目前為止你使用的大多數函式都是從日期中擷取特定部分,而 DATEFROMPARTS() 則完全相反:它會用三個數字(年份、月份、日期)來建立一個日期。

語法為: DATEFROMPARTS(year, month, day)

你也可以把會回傳數值的運算式當作此函式的參數,例如: DATEFROMPARTS(YEAR(date_expression), MONTH(date_expression), 2)

在本練習中,你會從 voters 資料表查詢資訊,包括 first_vote_date 的年份與月份。接著,你會建立一個新的日期欄位,代表首次投票當月的第 1 天。

本練習屬於課程

SQL Server 的資料操作函式

檢視課程

練習說明

  • 選出首次投票的年份。
  • 選出首次投票日期的月份。
  • 建立一個日期,作為首次投票當月的月初。

動手互動練習

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

SELECT 
	first_name,
	last_name,
    -- Select the year of the first vote
   	___(first_vote_date) AS first_vote_year, 
    -- Select the month of the first vote
	___(first_vote_date) AS first_vote_month,
    -- Create a date as the start of the month of the first vote
	___(___, ___, 1) AS first_vote_starting_month
FROM voters;
編輯並執行程式碼