简体   繁体   中英

Convert year (aaaa) and quarter (1 to 4) to Datetime in SQL Server

I am working on datazen and I have a year column (2015, 2016, 2013, ...) and a quarter (1 or 2 or 3 or 4) column. I want to convert them to a new column of data type datetime . I have searched a little and I found another SO question here .

The answer on that page was:

Select 
    dateadd(day, -1, dateadd(year, @year - 1900, dateadd(quarter, @qq, 0)))

I think it is the solution but I am having difficulty understanding it and I don't want (if possible) to use variables, but rather just convert in the query.

In SQL Server 2012+, you would use datefromparts() to get the first day of the quarter:

select datefromparts( YearColumn, QuarterColumn * 3 - 2, 1)

The strange dateadd() expression is used to get the first day of the year.

为什么不呢?

SELECT DATEADD(q, @qq - 1, DATEFROMPARTS(@year, 1, 1))

The answer to the other question is a bit of a hack to prevent issues with different date formats set on different databases. Basically, if we treat everything as a date, then we don't have to worry about the MANY different ways to format a date.

Here's a breakdown of how that other answer works:

dateadd(quarter, @qq, 0)

It first creates a date based off of the quarter, using 0 as the base date. This will generate one of 4 values: 1/1/1900, 4/1/1900, 7/1/1900, and 10/1/1900 (this probably changes based on the locality of the server, I'm using US).

dateadd(year, @year-1900, [date from the quarter dateadd function]

The second part takes the date from the first part, determines how many years have elapsed since 1900, and adds that many years to the first date. If the year that is being used is 2016, then 116 years is added. this will result one of these 4 values: 1/1/2016, 4/1/2016, 7/1/2016, 10/1/2016 (again US locality).

dateadd(day, -1, [date from previous function]

The last part takes the first day from each quarter and converts it to the LAST day of each quarter. this may not be a necessary part of the answer for you.

As @Gordon Linoff answered, a cleaner approach is the datefromparts function, which is only available in SQL Server 2012+.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM