8

I want to split a datetime column so that the year and the month both have their own column in a select statement output. I also want to have a column by week of the year, as opposed to specific date.

Basically, I want separate year, month, and week columns to show up in my select statement output.

4

3 回答 3

12

尝试使用DatePart如下所示的函数:

select
  datepart(year,Mydate), 
  datepart(month,Mydate),
  datepart(week,Mydate)
From
  MyTable

注意:如果您需要按ISO 8601标准计算周数,那么您需要使用datepart(iso_week,Mydate)

你也可以看看DateName函数

select
  datename(month,Mydate)
From
  MyTable
于 2013-10-02T14:33:46.263 回答
3

这是另一种方式。使用 SQL Server 的 YEAR() 和 MONTH() 函数。对于一周,我使用@DMK 指出的 datepart(week,Mydate) 。

SELECT YEAR(MyDate), MONTH(MyDate), DATEPART(WEEK,Mydate) From YourTable
于 2013-10-02T15:14:51.853 回答
0

检查这个

select datepart(Month,DateColumn) Mnth,datename(Month,DateColumn) MnthName,datepart(Year,DateColumn) Year1,((day(DateColumn)-1) / 7) + 1 week from dbo.Table
于 2013-10-02T14:44:42.553 回答