查询最近6个月的数据,按月份名称显示

时间:2014-07-29 00:17:44

标签: sql sql-server

我想获得最近6个月的计数记录,并每月显示一次。如果月份没有任何记录,我需要显示0。

我的查询是

DECLARE @Date1 DATETIME, @Date2 DATETIME
SET @Date1 = GETDATE()
SET @Date2 = DateAdd(month, -6, Convert(CHAR(10), @Date1, 121))

SELECT 
    DATENAME(MONTH,IssueDate) [Month Name], COUNT(1) [Count]
FROM 
    CompetitiveProcess
WHERE 
    IssueDate BETWEEN @Date2 AND @Date1
GROUP BY 
    YEAR(IssueDate), MONTH(IssueDate), DATENAME(MONTH, IssueDate)

但是没有显示没有任何行的月份。任何人都可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

只需使用递归CTE生成日期,然后使用left outer join来获取数据:

with dates as (
      select cast(getdate() - day(getdate()) + 1 as date) as monthstart,
             cast(dateadd(month, 1, getdate()) - day(getdate()) as date) as monthend,

             0 as lev
      union all
      select dateadd(month, -1, monthstart), 
             dateadd(day, -1, monthstart),
             lev + 1
      from dates
      where lev < 6
     )
SELECT DATENAME(dates.monthstart, IssueDate) as [Month Name],
       COUNT(cp.issuedate) as [Count]
FROM dates left outer join
     CompetitiveProcess cp
     on IssueDate BETWEEN dates.monthstart and dates.monthend
GROUP BY YEAR(dates.monthstart), MONTH(dates.monthstart), DATENAME(MONTH, dates.monthstart);