Skip to content
Advertisement

Create table with the week numbers of the last 6 months, with their respective month and year. SQL Server

I’m trying to get a table that contains the week number of the last 6 months. I found some code in github, and I modified it to accomplish my goal.

This what I have:

— 2019 only used to show the info from 2020 and above, because I don’t want the week number of 2019 or below

I get this result :

result of the query

The problem is that week 5 is repeated because apparently that week number is between 2 different months, but I just want to keep one of the results no matter the month or year, I want the week number to appear just once.

Is there a way to do this?

Advertisement

Answer

Sure, use GROUP BY in your query and pick either the MAX or MIN value of month_number for each year and week_number. Here’s an example, but I’m using a recursive CTE rather than that clunky query that relies on a table that has a limited number of numbers in it.

I get these results:

If I chose MIN instead of MAX I would get the same results, but week 5 would be assigned to month 1.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement