Date

按月將日期範圍(時間戳)分成相等的部分-SQL Server

  • June 30, 2020

專家,有一個關於將日期範圍按月分成相等部分的問題,包括時間部分

範例 - 從日期 - 06/29/2020 09:00:00 到今天 - 06/29/2021 09:00:00

想要將此日期範圍分成十二等份,如下所示

06/29/2020 09:00:00 - 06/30/2020 12:59:59
07/01/2020 00:00:00 - 07/31/2020 12:59:59
.........
.......
06/01/2021 00:00:00 - 06/29/2021 09:00:00

我不能編寫遞歸 CTE,因為這是我正在執行的 sql 突觸模組。

通過下面的查詢,我可以拆分日期部分,但時間部分沒有像上面那樣正確出現。請幫助我,因為這阻礙了我的發展

declare @FromTs DATETIME
declare @ToTs DATETIME
SET @FromTs = GetDate()
SET @ToTs = DATEADD(month, 12, @FromTs)

;WITH n(n) AS 
(
   SELECT ROW_NUMBER() OVER (ORDER BY [object_id])-1 FROM sys.all_columns
),
d(qi,qrt,qtt,n,f,t,md,bp,ep,rn) AS  
(
   SELECT 
   ,n.n, @FromTs, @ToTs, 
   DATEDIFF(MONTH, @FromTs, @ToTs),
   DATEADD(MONTH, n.n, DATEADD(DAY, 1-DAY( @FromTs),  @FromTs)),
   DATEADD(DAY, -1, DATEADD(MONTH, 1, DATEADD(MONTH, n.n, 
   DATEADD(DAY, 1-DAY( @FromTs),  @FromTs))))
   FROM n INNER JOIN <datetbl> AS d 
   ON @ToTs >= DATEADD(MONTH, n.n-1, @FromTs)
)
SELECT qi,qrt,qtt,
new_from_date = CASE n WHEN 0  THEN f ELSE bp END,
new_to_date   = CASE n WHEN md THEN t ELSE ep END,rn
FROM d WHERE md >= n
WITH 
-- Range borders
src_data AS (SELECT CAST('2020-06-29 09:00:00' AS DATETIME) AS fromdate, 
                   CAST('2021-06-29 09:00:00' AS DATETIME) AS todate),
-- numbers table
numbers AS (SELECT 0 num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3
            UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
            UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11)                         
-- The query
SELECT num + 1 id, 
      DATEADD(SECOND, num * DATEDIFF(SECOND, fromdate, todate) / 12, fromdate) fromdate,
      DATEADD(SECOND, (num + 1) * DATEDIFF(SECOND, fromdate, todate) / 12, fromdate) todate
FROM src_data, numbers
ORDER BY id;

小提琴

範圍被分成相等(以秒為單位)的部分。您可以更改計算粒度(例如,使用HOURS代替SECOND),零件長度將自動調整和四捨五入。

您可以將CTE 替換為從tonumbers獲取/生成整數列表的任何其他方法,並將查詢中使用的除數參數化(例如,可以替換為 , )。0``parts_amount-1``12``SELECT COUNT(num) FROM numbers

引用自:https://dba.stackexchange.com/questions/270104