简体   繁体   中英

How do I write query if I want 1st day of the month falls in 1st week in T-SQL

How do I write query if I want 1st day of the month falls in 1st week. my report needs to show data from SUN-SAT.so, if I run the report on anyway current week, it should only show the data for the previous week from SUN-Sat. Even though 10/27 falls in the 5th week of October , I am required to show as 10/27- 11/02 falls in the first week of November since November 1 falls in the first week of November.

Here it is how I want to display the date-range in my report for the month of November. and the same logic applies for every month.

Week 1 10/27 to 11/02

Week 2 11/03 to 11/09

Week 3 11/10 to 11/16

Week 4 11/17 to 11/23

Week 5 11/24 to 11/30

so, I am not counting till 4th week of October not the 5th one because I am counting 5th week as week 1 for November.

like wise, the first week of JAN will be 12/29 till 01/04 . I don't want to count 5th week of December because if I count, there will be duplication.

Thank you. I appreciate it.

In simpler terms, an entire week 'belongs' to a specific month based on whatever month the Saturday of that week lies in. Then you want to work backwards and calculate for a given month, the set of all weeks that belong to that month.

This will give you the forward calculation:

declare @date date = getdate();
select month(dateadd(day,7+datediff(day,@date,'2000-01-01')%7,@date))

And the reverse calculation:

declare @year int = 2013
declare @month int = 11
select
  datefromparts(@year,@month,1) as month,
  dateadd(day,i*7+datediff(day,datefromparts(@year,@month,1),'2000-01-01')%7-6,datefromparts(@year,@month,1)) week_start,
  dateadd(day,i*7+datediff(day,datefromparts(@year,@month,1),'2000-01-01')%7  ,datefromparts(@year,@month,1)) week_end
from (values(1),(2),(3),(4),(5)) wk(i)
  • I use datediff(day,@date,@known_date) instead of datepart(dw,@date) because it is deterministic.

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