我正在尝试根据周三到周三的报告周运行报告。 我找到了许多说明获得正确日期的例子,例如:
DATEADD(DAY, -5, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0))
问题是这些似乎只适用于当前周。上面的例子给出了15/11/17,这对于今天(24/11/2017)是正确的,但在星期日(2017年11月26日)它将得到22/11/2017时是不正确的。
如果我查看 22-28 / 11/2017 (周三至周二)之间的报告,我应该看到 15-22 / 11/2017 <的报告/ p>
29/11&amp; 2017年5月12日该报告应来自 22-29 / 11/2017
任何帮助表示赞赏!
答案 0 :(得分:2)
试试这个方法
SELECT
*,
CASE WHEN [wensday]>reportDate THEN DATEADD(WEEK,-2,[wensday]) ELSE DATEADD(WEEK,-1,[wensday]) END [from date],
CASE WHEN [wensday]>reportDate THEN DATEADD(WEEK,-1,[wensday]) ELSE [wensday] END [to date]
FROM
(
SELECT
reportDate,
-- monday of this week
--DATEADD(DAY,DATEDIFF(DAY,0,reportDate)/7*7,0) [monday],
-- wensday of this week
DATEADD(DAY,2,DATEADD(DAY,DATEDIFF(DAY,0,reportDate)/7*7,0)) [wensday]
FROM
(
SELECT CAST('20171115' AS date) reportDate
UNION ALL
SELECT CAST('20171121' AS date) reportDate
UNION ALL
SELECT CAST('20171122' AS date) reportDate
UNION ALL
SELECT CAST('20171123' AS date) reportDate
UNION ALL
SELECT CAST('20171124' AS date) reportDate
UNION ALL
SELECT CAST('20171129' AS date) reportDate
UNION ALL
SELECT CAST('20171205' AS date) reportDate
) test
) q
内联算法
DECLARE @reportDate date=GETDATE()
DECLARE @Wensday date=DATEADD(DAY,2,DATEADD(DAY,DATEDIFF(DAY,0,@reportDate)/7*7,0))
DECLARE @FromDate date=CASE WHEN @Wensday>@reportDate THEN DATEADD(WEEK,-2,@Wensday) ELSE DATEADD(WEEK,-1,@Wensday) END
DECLARE @ToDate date=DATEADD(WEEK,1,@FromDate)
SELECT @reportDate,@Wensday,@FromDate,@ToDate
答案 1 :(得分:1)
您可以使用DATEFIRST将第1-7天分配给星期三 - 星期二
无论你在这里放什么日期,它都会在周三之前返回
接下来的星期二仅仅是6天之后。
-- Wednesday will be 1 when we use datepart dw
SET DATEFIRST 3;
DECLARE @ReportDate DATE
SET @ReportDate = '2017-11-26'
SELECT
DATEADD( d,
-(DATEPART(dw,@ReportDate)-1),
@ReportDate
)
答案 2 :(得分:1)
试试这个......
DECLARE @fDt as date,@fDtR as date
set @fDt = '11/15/2017'
SET DATEFIRST 3
SELECT @fDtR = DATEADD(d,-6-(DATEPART(dw,@fDt)),@fDt)
print @fDtR
答案 3 :(得分:0)
你可以试试这个
select * from youtablename where yourdatefield <=
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,0)) and yourdatefield >
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,-7))
从这里你将得到上周三
select
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,0))
从此你将持续到上周三
select dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,-7))
这样您就可以找到周三到周三的数据。