2016-07-25 96 views
0

我想要計數。不知道我是否可以使用計數函數或使用case語句。每月重複計數

我要計數的ID,但如果計數每每個月該ID的EndDate_YYYYMM> = StartDate_YYYYMM

例如:

ID StartDate_YYYYMM EndDate_YYYYMM 
1  201601    201606 

期望的結果: 「接合」

StartDate_YYYYMM  Count 
    201601     1 
    201602     1 
    201603     1 
    201604     1 
    201605     1 
    201606     1 
    201607 

回答

2

這不像你可能期望的那樣直截了當。這主要是由於你的問題有幾個問題,它們是:

  • 你的表結構是未知的(下次添加一些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

0

如果我理解正確你的問題,然後您正在查找的劇本是:

SELECT tab.StartDate_YYYYMM 
     , COUNT(*) AS [Count] 
FROM YourTable tab 
WHERE EndDate_YYYYMM >= StartDate_YYYYMM 
GROUP BY tab.id 
     , tab.StartDate_YYYYMM