Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

Tags:

sql

sql-server

I have a Query where I get the WeekDay of a date but by default:

  • Sunday = 1

  • Moday = 2

  • etc.

The function is:

DATEPART(dw,ads.date) as weekday 

I need the result so:

  • Sunday = 7

  • Monday = 1

  • etc.

Is there any shortcut to do this? Or I will have to do a CASE statement?

like image 551
VAAA Avatar asked Jul 22 '14 00:07

VAAA


People also ask

What does DW mean in SQL?

After DATEFIRST defines the first day of the week for SQL Server, you can rely on DATEPART to return integer values when dw (day of week) is. the DATEPART.


2 Answers

This will do it.

SET DATEFIRST 1;  -- YOUR QUERY 

Examples

-- Sunday is first day of week set datefirst 7;  select DATEPART(dw,getdate()) as weekday   -- Monday is first day of week set datefirst 1; select DATEPART(dw,getdate()) as weekday 
like image 156
SQLChao Avatar answered Sep 19 '22 09:09

SQLChao


You can use a formula like:

(weekday + 5) % 7 + 1 

If you decide to use this, it would be worth running through some examples to convince yourself that it actually does what you want.

addition: for not to be affected by the DATEFIRST variable (it could be set to any value between 1 and 7) the real formula is :

(weekday  + @@DATEFIRST + 5) % 7 + 1 
like image 43
Greg Hewgill Avatar answered Sep 17 '22 09:09

Greg Hewgill