How to get one week data in SQL

Bala Narasimha Challa 466 Reputation points
2021-03-01T05:08:20.173+00:00

Hi Team,
Have code bellow like but am not getting proper week start and end dates. Please help on same
SELECT DATEADD(DAY, -1 - DATEPART(WEEKDAY, [Report Generated On]), [Report Generated On]) AS StartDate
, DATEADD(DAY, 5 - DATEPART(WEEKDAY, [Report Generated On]), [Report Generated On]) AS EndDate
,DATEPART(ww,[Report Generated On]) WeekNumber
,[Status]
,COUNT([MF No]) BookingCount
FROM tblName
where [Report Generated On] >='2021-02-19'
AND [Report Generated On] <'2021-02-26'
group by DATEADD(DAY, -1 - DATEPART(WEEKDAY, [Report Generated On]), [Report Generated On])
, DATEADD(DAY, 5 - DATEPART(WEEKDAY, [Report Generated On]), [Report Generated On])
,DATEPART(ww,[Report Generated On])
,[Status]

My Results:
72770-image.png

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,584 questions
0 comments No comments
{count} votes

Accepted answer
  1. MelissaMa-MSFT 24,176 Reputation points
    2021-03-01T06:36:11.927+00:00

    Hi @Bala Narasimha Challa ,

    For this type of problem we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data, enough to illustrate all angles of the problem. We also need to see the expected result of the sample.

    What is your expected first day of one week? Sunday?Monday? Another day?

    Sunday is the default one. If you would like to set aother weekday as first day of one week, you could add SET DATEFIRST.

    72834-untitled.png

    Your query could be as below:

      set datefirst 7  --default,set Sunday as first day of week, you could change this value accordingly   
      
    SELECT DATEADD(DAY, 1 - DATEPART(WEEKDAY, [Report Generated On]), [Report Generated On]) AS StartDate  
    , DATEADD(DAY, 7 - DATEPART(WEEKDAY, [Report Generated On]), [Report Generated On]) AS EndDate  
    ,DATEPART(ww,[Report Generated On]) WeekNumber  
    ,[Status]  
    ,COUNT([MF No]) BookingCount  
    FROM tblName  
    where [Report Generated On] >='2021-02-19'  
    AND [Report Generated On] <'2021-02-26'  
    group by DATEADD(DAY, 1 - DATEPART(WEEKDAY, [Report Generated On]), [Report Generated On])  
    , DATEADD(DAY, 7 - DATEPART(WEEKDAY, [Report Generated On]), [Report Generated On])  
    ,DATEPART(ww,[Report Generated On])  
    ,[Status]  
    

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful