在寻找截断日期时偶然发现了这两个帖子。
-- DATE TRUNCATE FORMAT
CAST(DATEADD(datepart, DATEDIFF(datepart, 0, date), 0) AS DATE)
这是我写的一个示例查询,可能会有所帮助:
DECLARE @datetime DATETIME = GETDATE() -- '2021-08-21 16:48:09.018'
SELECT
@datetime AS [Date Time]
, CAST(@datetime AS DATE) AS [Date]
, DATEPART(QUARTER, @datetime) AS [Quarter of Year]
, DATEDIFF(QUARTER, 0, @datetime) AS [Quarter Integer]
, DATEDIFF(QUARTER, 0, @datetime) - 1 AS [Previous Quarter Integer]
, DATEDIFF(QUARTER, 0, @datetime) + 1 AS [Next Quarter Integer]
, CAST(DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @datetime), 0) AS DATE) AS [Quarter Date 1]
, DATEFROMPARTS(YEAR(@datetime), (DATEPART(QUARTER, @datetime) * 3) - 2, 1) AS [Quarter Date 2]
, CAST(DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @datetime) - 1, 0) AS DATE) AS [Previous Quarter Start Date 1]
, DATEADD(QUARTER, -1, DATEFROMPARTS(YEAR(@datetime), (DATEPART(QUARTER, @datetime) * 3) - 2, 1)) AS [Previous Quarter Start Date 2]
, CAST(DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @datetime) + 1, 0) AS DATE) AS [Next Quarter Start Date 1]
, DATEADD(QUARTER, +1, DATEFROMPARTS(YEAR(@datetime), (DATEPART(QUARTER, @datetime) * 3) - 2, 1)) AS [Next Quarter Start Date 2]
, EOMONTH(DATEFROMPARTS(YEAR(@datetime), DATEPART(QUARTER, @datetime) * 3, 1)) AS [Quarter End Date 1]
, CAST(DATEADD(DAY, -1, DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @datetime) + 1, 0)) AS DATE) AS [Quarter End Date 2]
, CAST(DATEADD(DAY, -1, DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @datetime), 0)) AS DATE) AS [Previous Quarter End Date]
, CAST(DATEADD(DAY, -1, DATEADD(QUARTER, DATEDIFF(QUARTER, 0, @datetime) + 2, 0)) AS DATE) AS [Next Quarter End Date]