2017-08-28 125 views
2

我已经创建了一个查询来获得12个月的名称,也得到了该月的计数。使用我的查询,我逐月获取数据并获取月份名称。使用SQL Server获取12个月的数据计数名称?

但是在我的查询中,如果6月份在表格中没有任何数据,我将无法获得6月份的条目。我希望6月份也能显示0个数据。怎么可以做到这一点?我不知道。

这里是我的查询:

DECLARE @year nvarchar(max) 
SELECT @year = year(getdate()) 

SELECT 
    MONTH(InsertDateTime) AS m, 
    FORMAT(InsertDateTime, 'MMM-yy') AS Month, 
    COUNT(InsertDateTime) AS tally 
FROM 
    Comments 
WHERE 
    YEAR(InsertDateTime) = @year 
GROUP BY 
    FORMAT(InsertDateTime, 'MMM-yy'), MONTH(InsertDateTime) 

这是我回报O/P:

m | Month | tally 
1 Jan-17 1 
2 Feb-17 1 
3 Mar-17 10 
4 Apr-17 15 
5 May-17 20 
8 Aug-17 25 

这是我预期的O/P:

m | Month | tally 
1 Jan-17 1 
2 Feb-17 1 
3 Mar-17 10 
4 Apr-17 15 
5 May-17 20 
6 June-17 0 
7 July-17 0 
8 Aug-17 25 
9 Sep-17 0 
10 Oct-17 0 
11 Nav-17 0 
12 Dec-17 0 

此返回数据正确的,但在这里我不会再回到其他月份。像六月,七月,九月,十月,六月,十月十日进入表不是可用的。我想在这个月的时候还会收到0的价值。

+0

也许这可以帮助https://stackoverflow.com/questions/7893207/how-to-select-last-12-months-name-and-year-without-using-tables-using-sql-查询 – GuidoG

+0

可能重复[SQL组和按月的总和 - 默认为零](https://stackoverflow.com/questions/7121914/sql-group-and-sum-by-month-default-to-zero) – MatSnow

回答

1

使用即席日历表生成12份月:

/* @StartDate = truncate `getdate()` to the start of the year: */ 
declare @StartDate datetime = dateadd(year , datediff(year , 0, getdate()), 0) 

;with Months as (
select top (12) 
    m = row_number() over (order by number) 
    ,[Month] = dateadd(month, row_number() over (order by number) -1, @StartDate) 
    , NextMonth = dateadd(month, row_number() over (order by number), @StartDate) 
    from master.dbo.spt_values 
) 
select 
    m.m 
    , Month = format(m.Month, 'MMM-yy') 
    , tally = count(c.InsertDateTime) 
from Months m 
    left join Comments c 
    on c.InsertDateTime >= m.Month 
    and c.InsertDateTime < m.NextMonth 
group by m.m, format(m.Month, 'MMM-yy') 
order by m 

rextester演示:http://rextester.com/NNVI43016

回报:

+----+--------+-------+ 
| m | Month | tally | 
+----+--------+-------+ 
| 1 | Jan-17 |  3 | 
| 2 | Feb-17 |  0 | 
| 3 | Mar-17 |  2 | 
| 4 | Apr-17 |  0 | 
| 5 | May-17 |  0 | 
| 6 | Jun-17 |  0 | 
| 7 | Jul-17 |  0 | 
| 8 | Aug-17 |  0 | 
| 9 | Sep-17 |  0 | 
| 10 | Oct-17 |  0 | 
| 11 | Nov-17 |  0 | 
| 12 | Dec-17 |  1 | 
+----+--------+-------+ 

这样做的,因为它没有调用函数的额外优势在较大的表Comments的列中,并且它正在使用SARGable条件进行连接。

参考:

+0

我有尝试这个解决方案,但我没有得到六月,七月份的名称,也没有顺序在月 – Edit

+0

@编辑我已经添加了一个演示,并包括一个'order by'。请仔细检查您对代码的适应情况,以确认您已经移除了可能导致“左连接”隐式成为“内连接”的“where”子句。 – SqlZim

+0

你好我有我的答案,再次感谢你 – Edit

0

要么加入到派生表:

SELECT s.m,s.month,COALESCE(t.tally,0) as tally 
FROM (SELECT 1 as m, 'Jan-17' as Month UNION ALL 
     SELECT 2 as m, 'Feb-17' as Month UNION ALL 
     ...) s 
LEFT JOIN (Your Query) t 
ON(s.m = t.m and s.month = t.month) 

或者,如果你已经有了一个time表,然后用它来代替。

相关问题