我有一个查询,我按周使用DatePart(ww,[TimeEntryDate])对该列进行分组,并返回周数。我想显示周结束日期,并希望始终是一个星期六。
这是完整的查询
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
答案 0 :(得分:2)
您可以尝试以下
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
编辑:开始日期的设置取决于您的语言设置。周日美国英语默认值为7,但您需要验证您的设置并相应地调整计算。您可以使用
验证您的设置,以确定哪一天是一周的开始日期SELECT @@DATEFIRST;
此查询将说明不同之处:
SET LANGUAGE Italian;
GO
SELECT @@DATEFIRST;
GO
SET LANGUAGE us_english;
GO
SELECT @@DATEFIRST;
您还可以按如下方式设置周开始日期。
SET DATEFIRST 1
答案 1 :(得分:0)
这将为您提供任何一周的星期六日期:(来自@mwigdahl的this post提供)
**注意:您不需要CONVERT()函数,但它使其更具可读性*
CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, @date), @date)), 101)
这是一个证明它的测试:
DECLARE @date smalldatetime
SET @date = '7/1/11'
DECLARE @week int
SET @week = datepart(ww, @date)
WHILE @week <= 32 --just to take the test through July
BEGIN
SELECT
@week,
@date,
CONVERT(varchar(50), (DATEADD(dd, @@DATEFIRST - DATEPART(dw, @date), @date)), 101)
SET @date = @date + 1
SET @week = datepart(ww, @date)
END