SQL 查询 return 每月行数很慢
SQL query to return count of monthly rows is slow
所以,原来的查询很简单。
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
创建一个包含 12 个月的 table 并与第一个查询的结果进行左连接。类似于:
;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
所以,原来的查询很简单。
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
创建一个包含 12 个月的 table 并与第一个查询的结果进行左连接。类似于:
;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