上周的同比数据

时间:2016-08-24 19:28:32

标签: mysql date

我目前正在编写一个查询,它将在上周提供数据(假设" SALES")和同一周的去年数据。这是我必须得到的上周数据,它工作正常:

Set DATEFIRST 1 
Select DATEPArt(dd, DateAdded) AS 'Day of the Month', 
       count(*)AS 'Number of Users'
from TABLE1
Where DateAdded >= dateadd(day, -(datepart(dw, getdate()) + 6), CONVERT(date,getdate()))
  AND DateAdded <  dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) 
Group by DATEPArt(dd, DateAdded)
Order by 'Day of the Month'   

现在我想添加另一个专栏,它会在同一周给我去年的数据。这就是我的想法:

Set DATEFIRST 1 
Select DATEPArt(dd, DateAdded) AS 'Day of the Month', 
       count(*)AS 'Number of Users'
from TABLE1
Where DateAdded >= DATEADD(yy,DATEDIFF(yy,0,GETDATE())-1,0)
  AND DateAdded < DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0)
  AND DateAdded >= dateadd(day, -(datepart(dw, getdate()) + 6), CONVERT(date,getdate()))
  AND DateAdded <  dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
Group by DATEPArt(dd, DateAdded), DateAdded
Order by 'Day of the Month'   

问题是我仍在接受上周的数据(今年,我需要它去年)。这让我相信错误必须在某处:

DateAdded >= DATEADD(yy,DATEDIFF(yy,0,GETDATE())-1,0)
AND DateAdded < DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0)

我感谢所有人的帮助!!

1 个答案:

答案 0 :(得分:1)

您正在寻找OR条件

WHERE (DateAdded >= DATEADD(yy,DATEDIFF(yy,0,GETDATE())-1,0)
  AND DateAdded < DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0))

OR (DateAdded >= dateadd(day, -(datepart(dw, getdate()) + 6), CONVERT(date,getdate()))
  AND DateAdded <  dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())))