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

后端 未结 12 611
[愿得一人]
[愿得一人] 2020-12-23 16:27

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

  • Sunday = 1

  • Moday = 2

  • etc.

12条回答
  •  失恋的感觉
    2020-12-23 17:02

    You can use this formula regardless of DATEFIRST setting :

    ((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - [first day that you need] ) % 7) + 1;
    

    for monday = 1

    ((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 1 ) % 7) + 1;
    

    and for sunday = 1

    ((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 7 ) % 7) + 1;
    

    and for friday = 1

    ((DatePart(WEEKDAY, getdate()) + @@DATEFIRST + 6 - 5 ) % 7) + 1;
    

提交回复
热议问题