Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First Monday of the Year in SQL Server

How can I find "First Monday of the Year" using T-SQL ?

like image 778
HOY Avatar asked Nov 23 '12 08:11

HOY


People also ask

How do I get the first Monday of the week in SQL?

Option 2: Monday as the First Day of the Week Now, let's take a look at an expression that returns Monday as the first day of the week: SELECT DATEADD(week, DATEDIFF(week, 0, RegistrationDate - 1), 0) AS Monday; In the expression above, we add the specified number of weeks to the 0 date.

How do I get the first day of year in SQL?

Here's a fairly simple way; SELECT DATEFROMPARTS(YEAR(GETDATE()), 1, 1) AS 'First Day of Current Year'; SELECT DATEFROMPARTS(YEAR(GETDATE()), 12, 31) AS 'End of Current Year'; It's not sexy, but it works. Only available starting from Sql Server 2012.


1 Answers

Here's the example from the link ngruson posted (http://sqlbump.blogspot.nl/2010/01/first-monday-of-year.html):

DECLARE @Date datetime
DECLARE @Year int = 2012

SET @Date = DATEADD(YEAR, @Year - 1900, 0)

SELECT DATEADD(DAY, (@@DATEFIRST - DATEPART(WEEKDAY, @Date) + 
    (8 - @@DATEFIRST) * 2) % 7, @Date)

The above returns:

2012-01-02 00:00:00.000
like image 150
Cᴏʀʏ Avatar answered Sep 18 '22 15:09

Cᴏʀʏ