我有一个查询显示付款次数,按SQL Server 2012中的周数分组。
SELECT
DATEPART(wk, FPP.UPLOAD_DATE) AS "Date by week",
COUNT(DISTINCT FPP.ID) AS "Number of Bills")
FROM
FACT_PAY_PAYMENT FPP
GROUP BY
DATEPART(wk, FPP.UPLOAD_DATE);
小问题,当我执行此代码时,我会收到周数,但我想要一周的开始日期。
例如,现在我收到以下输出:
Date by week Number of Bills
---------------------------------
40 7
我想收到的是:
Date by week Number of Bills
---------------------------------
2015-09-28 7
答案 0 :(得分:4)
首先,你必须确定什么是周SELECT @@DATEFIRST;
的Datefirst,
在我的计算机中Sunday
是First day of week
DECLARE @dt DATE = '2015-09-08';
SELECT DATEADD(wk,DATEDIFF(wk,7,@dt),6) AS Datebyweek
结果
Datebyweek
2015-09-06 00:00:00.000
答案 1 :(得分:1)
使用DATEDIFF()
从开头获取周数,然后DATEADD()
获取第一个日期。例如;
DECLARE @date DATETIME = GETDATE()
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, @date) , 0) FirstDayOfWeek
您可以将其应用于您的查询,将@date替换为您的列名。就像;
SELECT
DATEADD(WEEK, DATEDIFF(WEEK, 0, FPP.UPLOAD_DATE) , 0) AS "Date by week",
COUNT(DISTINCT FPP.ID) AS "Number of Bills"
FROM
FACT_PAY_PAYMENT FPP
GROUP BY
DATEADD(WEEK, DATEDIFF(WEEK, 0, FPP.UPLOAD_DATE) , 0);
答案 2 :(得分:1)
请尝试
DECLARE @d AS DATETIME =GETDATE();
SELECT DATEPART(ISO_WEEK,@d) AS WeekIndex
,DATEADD(DAY,DATEPART(WEEKDAY,@d) * (-1) /* The following "+1" is depending on system's culture, look at DATEFIRST !!! */ + 1 ,@d) AS MondayForThisWeek
这将返回给定日期的本周指数和本周的周一。
了解系统文化的一些问题(特别是DATEFIRST !!!),年度结束时的周指数和一般日期(包括时间成分)。
答案 3 :(得分:0)
以下功能对我有帮助:
CREATE FUNCTION [dbo].[fn_GetFirstDateOfWeek] (@YearNum int, @WeekNum int)
RETURNS datetime
AS
BEGIN
DECLARE @FirstWeekDay As Date;
SET @FirstWeekDay = dateadd (week, @WeekNum, dateadd(year, @YearNum-1900, 0)) - 4 - datepart(dw, dateadd(week, @WeekNum, dateadd (year, @YearNum-1900, 0)) - 4) + 1
RETURN @FirstWeekDay
END