Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Comment fractionner des plages de dates en fonction des mois dans SQL Server 2005

Utilisation de CTE :

DECLARE @Begin DATETIME
DECLARE @End DATETIME

SELECT @Begin = '20110101', @End = '20120101'

;WITH ranges(DateFrom, DateTo) AS
(
  SELECT @Begin, DATEADD(DAY, -1, DATEADD(MONTH, 1, @begin))
  UNION ALL
  SELECT DATEADD(month, 1, DateFrom), DATEADD(DAY, -1, DATEADD(MONTH, 2, DateFrom))
  FROM ranges
  WHERE DateFrom < @End
)
SELECT * FROM ranges
OPTION(MAXRECURSION 0)

Et n'utilisant pas CTE :

DECLARE @Begin DATETIME
DECLARE @End DATETIME

SELECT @Begin = '20110101', @End = '20120101'

SELECT DATEADD(MONTH, n.Number, @Begin) DateFrom, DATEADD(day, -1, DATEADD(MONTH, n.Number+1, @Begin)) DateTo
FROM master.dbo.spt_values n
WHERE 
    n.Number < DATEDIFF(MONTH, @begin, @end)
AND n.Type = 'P'

Si vous devez également inclure janvier 2012, utilisez ceci

DECLARE @Begin DATETIME
DECLARE @End DATETIME

SELECT @Begin = '20110101', @End = '20120101'

SELECT DATEADD(MONTH, n.Number, @Begin) DateFrom, DATEADD(day, -1, DATEADD(MONTH, n.Number+1, @Begin)) DateTo
FROM master.dbo.spt_values n
WHERE 
    n.Number <= DATEDIFF(MONTH, @begin, @end)
AND n.Type = 'P'

Et CTE :

DECLARE @Begin DATETIME
DECLARE @End DATETIME

SELECT @Begin = '20110101', @End = '20120101'

;WITH ranges(DateFrom, DateTo) AS
(
  SELECT @Begin, DATEADD(DAY, -1, DATEADD(MONTH, 1, @begin))
  UNION ALL
  SELECT DATEADD(month, 1, DateFrom), DATEADD(DAY, -1, DATEADD(MONTH, 2, DateFrom))
  FROM ranges
  WHERE DATEADD(month, 1, DateFrom) < @End
)
SELECT * FROM ranges
OPTION(MAXRECURSION 0)