由部分组成日期
到目前为止,您使用的大多数函数都是从日期中提取部分;而 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;