Weekly to Monthly Reports

妖精的绣舞 提交于 2019-12-08 07:52:02

问题


I was running weekly reports as in the below script. However, I now want to run monthly report so needed some assistance. Weekly:

SELECT * FROM TABLE WHERE 
(ARRIVAL_DATE>GETDATE()-7)//7 days before
AND 
(ARRIVAL_DATE<GETDATE()) //NOW

For monthly report, will below script be right if I run on every 1st?

SELECT Column1,...
FROM TableName
WHERE
MONTH(DateColumn) = MONTH(dateadd(dd, -1, GetDate()))
AND
YEAR(DateColumn) = YEAR(dateadd(dd, -1, GetDate()))

Thanks.


回答1:


Your logic looks okay, although I would use day instead of dd, because I think it is clearer.

However, your query will prevent the use of an index on datecolumn. The following is a "better" form of the logic, because it allows the use of an index:

where datecolumn >= dateadd(month, -1,
                            dateadd(day, 1 - day(getdate()), cast(getdate() as date))
                           ) and
      datecolumn < dateadd(day, 1 - day(getdate()), cast(getdate() as date))

This looks more complicated, but all the functions are on getdate(), so the engine can use an index. Also note the explicit conversion to date. getdate() returns a time component which might throw off the logic if datecolumn only has a date.




回答2:


where datecolumn between dateadd(mm, -1,getdate()) and getdate()



来源:https://stackoverflow.com/questions/27657759/weekly-to-monthly-reports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!