返回每月行数的SQL查询很慢

时间:2016-06-17 00:32:10

标签: sql-server sqlperformance

因此,原始查询非常简单。

select MONTH(DateColumn), COUNT(DateColumn)
from myTable
where YEAR(DateColumn) = '2014'
group by MONTH(DateColumn)
order by MONTH(DateColumn)

但是,其中一个月没有数据,我需要全部12个月。所以我忙着重新做它..我有一个解决方案,但它很慢。必须有更好的方法。

select o.MonthCount, coalesce(d.total,0) from (
select top 12 ROW_NUMBER() over (order by (select 12)) as MonthCount from myTable
) o outer apply (
select month(e.DateColumn) as mon, COUNT(e.DateColumn) as total
from myTable e 
where YEAR(e.DateColumn) = '2013' 
and o.monthcount = month(e.DateColumn) 
group by MONTH(e.DateColumn) 
) d 

1 个答案:

答案 0 :(得分:3)

创建一个包含12个月的表,并使用第一个查询的结果保持连接。类似的东西:

;with cte as (select 1 as m
union select 2
union select 3
union select 4
union select 5
union select 6
union select 7
union select 8
union select 9
union select 10
union select 11
union select 12)
select cte.m, ISNULL(m.c, 0)
from cte left join (
select MONTH(DateColumn) mon, COUNT(DateColumn) c
from myTable
where YEAR(DateColumn) = '2014'
group by MONTH(DateColumn)) i on i.mon = cte.m
order by cte.m