阅读量:0
在报表统计中,DATEADD函数可以用来进行日期的加减运算,从而实现对日期数据的灵活处理。以下是一些常见的技巧:
- 计算本月的开始日期和结束日期:
SELECT DATEADD(DAY, 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AS StartOfMonth, DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE()), 0)) AS EndOfMonth
- 计算上个月的开始日期和结束日期:
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0) AS StartOfLastMonth, DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) AS EndOfLastMonth
- 计算本周的开始日期和结束日期:
SELECT DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE())) AS StartOfWeek, DATEADD(DAY, 7 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE())) AS EndOfWeek
- 计算上周的开始日期和结束日期:
SELECT DATEADD(DAY, -6 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE())) AS StartOfLastWeek, DATEADD(DAY, 0 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE())) AS EndOfLastWeek
通过使用DATEADD函数,可以方便地实现对日期数据的灵活处理,帮助报表统计更加准确和便捷。