SQL Server - 选择过去12个月,包括没有记录的月份

时间:2016-06-07 16:04:02

标签: sql-server

我需要使用Select SQL for SQLServer为表中的最近12个月计数创建报告。到目前为止,我能够使用各种Stackoverflow答案创建以下内容。但是,如果没有数据,它就无法获得数月的输出。         以下几个链接对我有所帮助:  MSDN

 (I apologize for any indentation errors(I've tried Ctl+K))

该表有很多列,但我感兴趣的是lastupdatetimestamp

;WITH CTE_DatesTable
   AS 
(
 SELECT CAST(CURRENT_TIMESTAMP as datetime) AS lastupdatetimestamp
 UNION ALL
 SELECT DATEADD(m, -1, lastupdatetimestamp)
 FROM CTE_DatesTable
 WHERE DATEADD(m, -1, lastupdatetimestamp) > DATEADD(m, -12,CURRENT_TIMESTAMP )
)
SELECT [MONTH] ,
     [LAST_12_MONTHS]
FROM (  
SELECT MONTH(lastupdatetimestamp) AS   MonthNumber,
   DATENAME(MONTH,lastupdatetimestamp) AS [MONTH], 
   COUNT(*) AS [LAST_12_MONTHS]
 FROM FILES 
 GROUP BY MONTH(lastupdatetimestamp), 
    DATENAME(MONTH,lastupdatetimestamp)
    ) AS Data
 RIGHT OUTER JOIN
  (
        SELECT YEAR(lastupdatetimestamp) AS YearNumber
              ,MONTH(lastupdatetimestamp) AS MonthNumber
        FROM CTE_DatesTable
    ) AS DateTable
ON Data.MonthNumber = DateTable.MonthNumber 
ORDER BY DateTable.MonthNumber DESC

输出:


| MONTH     | LAST_12_MONTHS |
|-----------|--------------- |
|   (null)  |   (null)       |
|   (null)  |   (null)       |
|   (null)  |   (null)       |
|   (null)  |   (null)       |
|   (null)  |   (null)       |
|   (null)  |   (null)       |
|   June    |   45           |
|   May     |   23           |
|   (null)  |   (null)       |
|   (null)  |   (null)       |
|   (null)  |   (null)       |
|   (null)  |   (null)       |

必需的输出:


| MONTH     | LAST_12_MONTHS |
|-----------|--------------- |
|   July    |   46           |
|   Aug     |   56           |
|   Sep     |   45           |
|   Oct     |   45           |
|   Nov     |   44           |
|   Dec     |   87           |
|   Jan     |   6            |
|   Feb     |   56           |
|   March   |   664          |
|   April   |   56           |
|   May     |   23           |
|   June    |   45           |

到目前为止,我遇到了几个问题:

  1. 没有数据的月份即将发布为' null'

  2. 我得到了几个月的日历,而不是过去的12个月。

    非常感谢任何帮助。

    谢谢

1 个答案:

答案 0 :(得分:0)

以下是一个解决方案的想法:

exec(code1); exec(code2)