Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL display week ending dat when using DatePart(ww, Date)

I have a query where I am grouping by week using DatePart(ww , [TimeEntryDate]) for the column and it returns the week number. I would like to display the week ending date and like that to always be a saturday.

Here's the complete query

SELECT 
DatePart(year , [TimeEntryDate]) [YEAR],
DatePart(ww , [TimeEntryDate]) Week, 
CategoryId, 
SUM(TimeEntryDuration) "Total Hours"

  FROM [TIMETRACKER].[dbo].[aspnet_starterkits_TimeEntry]
  GROUP BY DatePart(year , [TimeEntryDate]),  DatePart(ww , [TimeEntryDate]) , CategoryId 
  ORDER BY 1,2,3

data 
Year    Week   Category  Total Hours
2010     1        1          10
2010     2         1         12
like image 462
Ronald McDonald Avatar asked Jun 22 '26 06:06

Ronald McDonald


1 Answers

You can try the following

SELECT DatePart(year , [TimeEntryDate]) [YEAR],
       DatePart(ww , [TimeEntryDate]) Week, 
       DATEADD(d, 7 - DATEPART(DW, [TimeEntryDate]), [TimeEntryDate]) as WeekEnding,
       CategoryId, 
       SUM(TimeEntryDuration) "Total Hours"  
  FROM [TIMETRACKER].[dbo].[aspnet_starterkits_TimeEntry]  
 GROUP BY DatePart(year , [TimeEntryDate]),  DatePart(ww , [TimeEntryDate]) , CategoryId 
 ORDER BY 1,2,3

EDIT: The settings for start date is based on your language settings. The U.S. English default is 7, Sunday, but you need to verify your settings and adjust the calculation accordingly. You can verify your settings to determine which day is the start of the week with

SELECT @@DATEFIRST;

This query will illustrate the difference:

SET LANGUAGE Italian;
GO
SELECT @@DATEFIRST;
GO
SET LANGUAGE us_english;
GO
SELECT @@DATEFIRST;

You can also set your week start date as follows.

SET DATEFIRST 1
like image 106
Leons Avatar answered Jun 23 '26 22:06

Leons