Find data between range of weeks sql server

Abhijit Ghosh 61 Reputation points
2022-06-30T15:07:17.917+00:00

I am trying to find out data from one of my table based upon weeks filter. My Date column is weekly grain. I need to find data from table part by part i.e. 15 weeks in one part. select * from Table where date column between (select MAX(datecolumn) from table) and (select MAX(Datecolumn)-15 from table), select * from Table where date column between (select MAX(datecolumn)-16 from table) and (select MAX(Datecolumn)-30 from table)

Developer technologies | Transact-SQL
SQL Server | Other
{count} votes

Accepted answer
  1. Bert Zhou-msft 3,436 Reputation points
    2022-07-01T05:25:30.8+00:00

    Hi,@Abhijit Ghosh

    Welcome to Microsoft T-SQL Q&A Forum!

    The information you provided is too little, we can't get the purpose accurately through your simple description, you can try this, untested, I don't know what other fields you have, if this can't be solved, please provide sample data to us.

    ;WITH cte AS  
    (  
       SELECT *,  
             ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DATE DESC) AS rn  
       FROM mytable  
    )  
    SELECT cte.ID,   
        MAX(mt.DATE) AS MAXDATE  
    FROM cte  
        INNER JOIN mytable mt ON cte.ID = mt.ID  
    WHERE rn = 1 and MAXDATE between dateadd(week, -15, MAXDATE) and dateadd(week, -30,MAXDATE)  
    GROUP BY cte.ID  
    

    Bert Zhou

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Naomi Nosonovsky 8,431 Reputation points
    2022-06-30T19:50:35.103+00:00

    Can you post your table structure, some input and desired output based on the input?

    declare @LatestDate date = (select top (1) DateColumn from table order by DateColumn DESC);

    declare @StartDate1 date = dateadd(week, -15, @LatestDate);

    declare @StartDate2 date = dateadd(week, -30, @LatestDate);

    select * from table where DateColumn between @StartDate1 and @LatestDate;

    select * from table where DateColumn between @StartDate2 and @StartDate1;

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.