This article explores the DATEPART SQL function and its use in writing t-SQL queries. In the previous article, SQL Convert Date Functions and Formats, we explored various data formats and convert them using SQL Convert function.
本文探讨了DATEPART SQL函数及其在编写t-SQL查询中的用法。 在上一篇文章SQL Convert Date函数和格式中 ,我们探讨了各种数据格式,并使用SQL Convert函数对其进行了转换。
Usually, WHEN we use dates in SQL Server tables. Sometimes, we require retrieving A specific part of the date such as day, month or year from the existing SQL tables. We can use THE DATEPART SQL function to do this.
通常,当我们在SQL Server表中使用日期时。 有时,我们需要从现有SQL表中检索日期的特定部分,例如日,月或年。 我们可以使用DATEPART SQL函数来执行此操作。
DATEPART SQL函数的语法 (The syntax for the DATEPART SQL function)
DATEPART (interval, date)
DATEPART(间隔,日期)
We need to pass two parameters in this function.
我们需要在此函数中传递两个参数。
- Interval: We specify the interval that we want to get from a specified date. The DATEPART SQL function returns an integer value of specific interval. We will see values for this in the upcoming section. 时间间隔 :我们指定要从指定日期开始的时间间隔。 DATEPART SQL函数返回特定间隔的整数值。 我们将在接下来的部分中看到此值。
- Date: We specify the date to retrieve the specified interval value. We can specify direct values or use expressions to return values from the following data types. 日期 :我们指定日期以检索指定的间隔值。 我们可以指定直接值或使用表达式从以下数据类型返回值。
- Date 日期
- DateTime 约会时间
- Datetimeoffset 日期时间偏移
- Datetime2 日期时间2
- Smalldatetime 小日期时间
- Time 时间
通过示例探索DATEPART SQL函数 (Explore the DATEPART SQL function with examples)
In this section, let’s explore DATEPART SQL with examples and different interval values.
在本节中,我们将使用示例和不同的间隔值探索DATEPART SQL。
Datepart | Description | Example | |
Year yyyy yy | To retrieve year from a specified date |
| |
Quarter q | To retrieve Quarter from a specified date |
|
|
Month Mm m | To retrieve Month from a specified date |
|
|
Dy / y | We get Day of year in a specified date. For example, Jan 1 2019 is the 1st day of the year, and Dec 31, 2019, is the 365th day of the year. |
|
|
Dd /d | It gives date from the specified date |
|
|
Wk Ww Week | We get week number of current date in specified date. We have 52 weeks in 2019. |
|
|
Hour Hh | It gives hour part from the specified date. |
|
|
Minute N | We can get Minute part of specified date using this. |
|
|
Second Ss s | We can retrieve Seconds from specified date using Seconds Datepart. |
|
|
millisecond, ms | It retrieves milliseconds value from the specified date. |
|
|
Microsecond MCS | It retrieves Microsecond value from a specified date. |
|
|
Nanosecond NS | It retrieves nanoSecond value from a specified date. |
|
|
TZoffset tz | TZOFFSET computes the time zone offset between the local time zone and GMT. |
|
|
日期部分 | 描述 | 例 | |
年 yyyy y | 从指定日期检索年份 |
| |
25美分硬币 q | 从指定日期检索季度 |
| |
月 嗯 米 | 从指定日期检索月份 |
| |
dy / y | 我们在指定的日期获得一年中的一天。 例如,2019年1月1日是一年中的第一天,而2019年12月31日是一年中的第365天。 |
| |
d / d | 从指定日期开始给出日期 |
| |
周 Ww 周 | 我们得到指定日期中当前日期的星期数。 我们在2019年有52周。 |
![]() | |
小时 h | 它给出了从指定日期开始的小时部分。 |
| |
分钟 ñ | 我们可以使用此获取指定日期的分钟部分。 |
![]() | |
第二 s s | 我们可以使用Seconds Datepart从指定日期检索Seconds。 |
| |
毫秒,毫秒 | 它从指定的日期检索毫秒值 。 |
| |
微秒 MCS | 它检索微秒 指定日期的值 。 |
| |
纳秒 NS | 它检索nanoSecond 指定日期的值 。 |
| |
偏移量 tz | TZOFFSET计算本地时区和GMT之间的时区偏移量。 |
|
Let’s use various DATEPART SQL function parameters in a single SQL statement. It helps us to understand the breakdown of a specified date.
让我们在单个SQL语句中使用各种DATEPART SQL函数参数。 它有助于我们了解指定日期的细分。
DECLARE @date DATETIME2= GETDATE();
SELECT @date;
SELECT DATEPART(YY, @date) AS Year,
DATEPART(QQ, @date) AS Quarter,
DATEPART(WK, @date) AS Week,
DATEPART(DY, @date) AS dayofYear,
DATEPART(MM, @date) AS Month,
DATEPART(DD, @date) AS Date,
DATEPART(hour, @date) AS Hour,
DATEPART(minute, @date) AS Minute,
DATEPART(second, @date) AS Second,
DATEPART(millisecond, @date) AS Millsecond,
DATEPART(microsecond, @date) AS Microsecond,
DATEPART(nanosecond, @date) AS Nanosecond;
ISO_WEEK (ISO_WEEK )
While working with dates, we might get different values in different countries of the world for following things.
在处理日期时,我们可能会在世界上不同的国家获得不同的价值。
- Week number 周数
- Day of the Week 一周中的天
It depends on the Country and language. In ISO 8601 weekday system, we consider a week in which Thursday comes. It is the most common week numbering system.
这取决于国家和语言。 在ISO 8601工作日系统中,我们考虑星期四到来的一周。 这是最常见的星期编号系统。
Accordingly, in the year 2004, the first week occurs from Monday, 29 December 2003 to Sunday, 4 January 2004.
因此,在2004年,第一周是从2003年12月29日星期一到2004年1月4日星期日。

First day of week | Last day of week | The first week of the year contains | Country |
Sunday | Saturday | 1 January, | United States |
Monday | Sunday | 1 January, | Most of Europe and the United Kingdom |
Monday | Sunday | 4 January, | ISO 8601, Norway, and Sweden |
一周的第一天 | 一周的最后一天 | 一年的第一周包含 | 国家 |
星期日 | 星期六 | 1月1日, | 美国 |
星期一 | 星期日 | 1月1日, | 欧洲大部分地区和英国 |
星期一 | 星期日 | 1月4日, | ISO 8601,挪威和瑞典 |
Let’s run the following query with DATEPART SQL to return ISO 8601 week and US week no.
让我们使用DATEPART SQL运行以下查询,以返回ISO 8601周和美国周号。
DECLARE @date datetimeoffset = '2008-01-06 00:00:00.000';
SELECT
DATEPART(ISO_WEEK, @date) AS 'ISO_WEEK',
DATEPART(wk, @date) AS 'US WEEK';
In the following screenshot, we can see for 6th January 2008, ISO week is first and US week is 2nd.
在以下屏幕截图中,我们可以看到2008年1月6日,ISO周为第一周,美国周为第二周。
Similarly, January 1st, 2012 is having the first week in ISO 8601 and week 53rd in US week.
同样,2012年1月1日是ISO 8601的第一周,而美国周是第53周。
DECLARE @date datetimeoffset = '2012-01-01 00:00:00.000';
SELECT
DATEPART(ISO_WEEK, @date) AS 'ISO_WEEK',
DATEPART(wk, @date) AS 'US WEEK';
Let’s look at one more example. For 3rd January 2010, we have 53rd ISO week and 2nd US week.
让我们再看一个例子。 在2010年1月3日,我们有ISO第53周和美国第2周。
DECLARE @date datetimeoffset = '2010-01-03 00:00:00.000';
SELECT
DATEPART(ISO_WEEK, @date) AS 'ISO_WEEK',
DATEPART(wk, @date) AS 'US WEEK';
指定星期几 (Specify day for the start of the week)
We can set the first day of the week with SQL DATEFIRST function. We can specify value 1 to 7. If we specify the value 1, it considers Monday as the first day of the week. We can refer to the following table for specifying a value in SQL DATEFIRST.
我们可以使用SQL DATEFIRST函数设置一周中的第一天。 我们可以指定值1到7。如果指定值1,则它将星期一视为一周的第一天。 我们可以参考下表在SQL DATEFIRST中指定一个值。
DATEFIRST Value | First day of week starts from |
1 | Monday |
2 | Tuesday |
3 | Wednesday |
4 | Thursday |
5 | Friday |
6 | Saturday |
7 | Sunday |
DATEFIRST值 | 一周的第一天从 |
1个 | 星期一 |
2 | 星期二 |
3 | 星期三 |
4 | 星期四 |
5 | 星期五 |
6 | 星期六 |
7 | 星期日 |
We can get current DATEFIRST value using system variable @@DATEFIRST. Execute the following query to get the default value of SQL DATEFIRST and the first day of the week.
我们可以使用系统变量@@ DATEFIRST获得当前的DATEFIRST值。 执行以下查询以获取SQL DATEFIRST的默认值和一周中的第一天。
SELECT @@DATEFIRST AS CurrentDateFIRSTValue,
CASE @@DATEFIRST
WHEN 7
THEN 'Sunday'
WHEN 6
THEN 'Saturday'
WHEN 5
THEN 'Friday'
WHEN 4
THEN 'Thursday'
WHEN 3
THEN 'Wednesday'
WHEN 2
THEN 'Tuesday'
WHEN 1
THEN 'Monday'
ELSE 'Invalid Value'
END AS FirstdayofWeek;
In the following screenshot, we can see in my system, it having SQL DATEFIRST value 7. It starts on the first day of the week from Sunday.
在下面的屏幕截图中,我们可以在系统中看到它SQL DATEFIRST值为7。它从星期日的一周的第一天开始。
Execute the following query to get the current week of the year. We can see 21st April 2019 is week 17 of the current year.
执行以下查询以获取一年中的当前星期。 我们可以看到2019年4月21日是本年的第17周。
DECLARE @OrderDate DATETIME2= GETDATE();
SELECT @OrderDate AS OrderDate,DATEPART(wk , @OrderDate) AS WeekofYear;

Suppose we want to change the first day of the week to Monday. We can do it using SET DATEFIRST command and specify a value from the table specified above.
假设我们要将一周的第一天更改为星期一。 我们可以使用SET DATEFIRST命令并从上面指定的表中指定一个值。
SET DATEFIRST 1;
DECLARE @OrderDate DATETIME2= GETDATE();
SELECT @OrderDate AS OrderDate, DATEPART(wk, @OrderDate) AS WeekofYear;
In the output, we can see the current week of the year is 16. It is because SQL considered Monday as the first day of the week.
在输出中,我们可以看到一年中的当前星期为16。这是因为SQL将星期一视为一周的第一天。
Let’s verify current DATEFIRST setting in the instance
让我们验证实例中的当前DATEFIRST设置
DATEPART SQL返回的默认值 (Default values returned by DATEPART SQL)
Suppose we do not have a date format such as yyyy-mm-dd hh:ss: Mmm. If we do not have a date datatype, we get default values as the output of DATEPART SQL.
假设我们没有日期格式,例如yyyy-mm-dd hh:ss:Mmm。 如果没有日期数据类型,则将获得默认值作为DATEPART SQL的输出。
In the following example, we want to retrieve values such as Year, Month, and Day. We are providing input in the form of hh:mm: ss.mmm.
在下面的示例中,我们要检索诸如Year,Month和Day的值。 我们以hh:mm:ss.mmm的形式提供输入。
SELECT DATEPART(year, '00:00:00.000') AS [Year],
DATEPART(month, '00:00:00.000') AS [Month],
DATEPART(day, '00:00:00.000') AS [Day],
DATEPART(dayofyear, '00:00:00.000') AS [Dayofyear],
DATEPART(weekday, '00:00:00.000') AS [WeekDay];
In earlier examples, we used variables in DATEPART SQL to get respective values. In the following query, we specified a variable with the datatype. Execute this query.
在较早的示例中,我们在DATEPART SQL中使用了变量来获取相应的值。 在以下查询中,我们指定了具有数据类型的变量。 执行此查询。
DECLARE @OrderDate TIME= '00:00:00.000';
SELECT DATEPART(year, @OrderDate) AS [Year],
DATEPART(month, @OrderDate) AS [Month],
DATEPART(day, @OrderDate) AS [Day],
DATEPART(dayofyear, @OrderDate) AS [Dayofyear],
DATEPART(weekday, @OrderDate) AS [WeekDay];
We get the following error message that datatype is not supported by date function DATEPART SQL.
我们收到以下错误消息,日期函数DATEPART SQL不支持数据类型。
具有Group By和Order By子句的DATEPART SQL (DATEPART SQL with Group By and Order By clause)
We can use the DATEPART SQL function with Group By clause as well to group data based on a specified condition.
我们可以将DATEPART SQL函数与Group By子句一起使用,也可以根据指定条件对数据进行分组。
Let’s create a sample table and insert hourly data in it.
让我们创建一个示例表并在其中插入每小时数据。
CREATE TABLE Orders
(OrderID INT IDENTITY(1, 1),
OrderDate DATETIME2
);
GO
INSERT INTO Orders(OrderDate)
VALUES(DATEADD(hh, -ROUND(60 * RAND(), 0), GETDATE()));
GO 500
Let’s view sample data in the Orders table.
让我们在“订单”表中查看示例数据。
SELECT *
FROM orders
ORDER BY Orderdate DESC;
Suppose we want to get hourly data from the Orders table. We can use the DATEPART SQL function in a Group By clause to get hourly data. Execute the following query, and in the output, you can see the count of hourly orders data. We further used Order By clause to sort results.
假设我们要从Orders表中获取每小时的数据。 我们可以在Group By子句中使用DATEPART SQL函数来获取每小时数据。 执行以下查询,然后在输出中,您可以看到每小时订单数据的计数。 我们进一步使用Order By子句对结果进行排序。
SELECT CAST(OrderDate AS DATE) OrderDate,
DATEPART(hour, OrderDate) [Hour],
COUNT(1) [Order Count]
FROM Orders
GROUP BY CAST(OrderDate AS DATE),
DATEPART(hour, OrderDate)
ORDER BY OrderDate,
[Order Count];
结论 (Conclusion)
In this article, we explore the use of SQL DATAPART function with examples. You should be familiar with this useful SQL function to improve your T-SQL coding skill. I hope you found this article helpful.
在本文中,我们将通过示例探索SQL DATAPART函数的用法。 您应该熟悉此有用SQL函数,以提高您的T-SQL编码技能。 希望本文对您有所帮助。