我正在创建一个应用程序,该应用程序应在仪表板中显示一个条形图,显示一个月内第1周到第周周的记录数:
Example (July):
Week 1 (2014-07-01 to 2014-07-05) = 30 records
Week 2 (2014-07-06 to 2014-07-12) = 15 records
Week 3 (2014-07-13 to 2014-07-19) = 50 records
Week 4 (2014-07-20 to 2014-07-26) = 24 records
Week 5 (2014-07-27 to 2014-07-31) = 6 records
我见过几个例子,但他们似乎都关注年度周。如果没有为该周添加记录,则报告应该在本周显示0。我见过的所有例子都使用Group By Date,如果本周有相应的记录,这只会输出一个计数。
答案 0 :(得分:1)
尝试以下功能,传递星期几,然后返回周
CREATE FUNCTION WeeksOfTheMonth(@MothEndDate DATETIME)
RETURNS
@DateOfMonth TABLE(
StartDate DATETIME,
EndDate DATETIME,
WeekNo INT
)
AS
BEGIN
DECLARE @NoOfWeeks AS INT,
@StartDateNo AS INT,
@EndDateNo AS INT,
@Count AS INT
SELECT
@NoOfWeeks = DATEPART(WEEK,DAY(@MothEndDate)),
@StartDateNo = 1,
@EndDateNo = 5,
@Count = 1
WHILE(@NoOfWeeks > 0)
BEGIN
INSERT INTO @DateOfMonth(StartDate, EndDate, WeekNo)
SELECT DATEADD(day, DATEDIFF (day, 1, DATEADD(month, DATEDIFF(month, 0, @MothEndDate), 0) -1) /7*7 + 5, @StartDateNo),
DATEADD(day, DATEDIFF (day, 1, DATEADD(month, DATEDIFF(month, 0, @MothEndDate), 0) -1) /7*7 + 6, @EndDateNo),
@Count
SELECT
@StartDateNo = @StartDateNo + 7,
@EndDateNo = @EndDateNo + 7,
@NoOfWeeks = @NoOfWeeks - 1,
@Count = @Count + 1
END
RETURN
END
称之为
SELECT * FROM WeeksOfTheMonth('31 Aug 2014')