在报表统计中,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函数,可以方便地实现对日期数据的灵活处理,帮助报表统计更加准确和便捷。