在報表統計中,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函數,可以方便地實現對日期數據的靈活處理,幫助報表統計更加準確和便捷。