這不像你可能期望的那樣直截了當。這主要是由於你的問題有幾個問題,它們是:
- 你的表結構是未知的(下次添加一些DDL)。
- 由於YYYYMM格式,我們必須假定您的日期存儲爲
VARCHAR
。
- 生成一個日期序列是最簡單的一個「日期」表,我們必須假設你沒有日期。
話雖這麼說,下面的查詢會產生你的目標的結果,因爲我的理解是正確的:
;
WITH CTE_DateTable
AS (
SELECT #t.ID,
CAST(#t.StartDate_YYYYMM + '01' AS DATE) AS StartDate,
CAST(#t.EndDate_YYYYMM + '01' AS DATE) AS EndDate
FROM #t
),
CTE_MinMaxDates
AS (
SELECT MIN(CTE_DateTable.StartDate) AS MinDate,
MAX(CTE_DateTable.EndDate) AS MaxDate,
DATEDIFF(MONTH, MIN(CTE_DateTable.StartDate), MAX(CTE_DateTable.EndDate)) AS Difference
FROM CTE_DateTable
),
CTE_Nums
AS (
SELECT ROW_NUMBER() OVER (ORDER BY ob.object_id) AS Num
FROM sys.all_objects AS ob
),
CTE_Months
AS (
SELECT DATEADD(MONTH, n.Num - 1, d.MinDate) AS MonthStart
FROM CTE_MinMaxDates d
CROSS JOIN CTE_Nums n
WHERE DATEADD(MONTH, n.Num - 1, d.MinDate) <= d.MaxDate
)
SELECT CAST(DATEPART(YEAR, m.MonthStart) AS VARCHAR) + SUBSTRING(CONVERT(NVARCHAR(6), m.MonthStart, 112), 5, 2) AS StartDate_YYYYMM,
COUNT(DISTINCT d.ID) AS Count
FROM CTE_DateTable AS d
INNER JOIN CTE_Months AS m ON m.MonthStart BETWEEN d.StartDate AND d.EndDate
GROUP BY m.MonthStart;
Working example