SQL速度:返回日期范围中的每个日期和每个日期的count()

时间:2017-03-19 14:07:52

标签: sql sql-server

我的目标是返回日期范围内的每个日期,并计算每个日期的所有记录。

MyTable
-------------------------------
| OrderId |   DateFinalized   |
-------------------------------
|   51    | 2016-1-3 12:50:34 |
|   55    | 2016-1-4 10:01:56 |
|   73    | 2016-1-4 11:52:02 |
|   93    | 2016-1-6 01:35:16 |
|   104   | 2016-1-6 02:40:47 |
-------------------------------

挑战在于包括没有订单的日期。使用上面的MyTable,如果日期范围介于2016-1-12016-1-6之间,则所需的输出为:

---------------------
|  MyDate  | Orders |
---------------------
| 2016-1-1 |   0    |
| 2016-1-2 |   0    |
| 2016-1-3 |   1    |
| 2016-1-4 |   2    |
| 2016-1-5 |   0    |
| 2016-1-6 |   2    |
---------------------

为了做到这一点,我使用此查询选择仅限日期,并在1秒内

declare @startdate datetime = '1/1/2016';
declare @enddate datetime = '1/1/2017';

with [dates] as (
    select convert(date, @startdate) as [date] 
    union all
    select dateadd(day, 1, [date])
    from [dates]
    where [date] < @enddate 
)
select 
[date]
from [dates] 
where [date] between @startdate and @enddate
order by [date] desc
option (maxrecursion 0)

当我选择按日期分组的订单计数时,如下所示,它也只需 1秒

declare @startdate datetime = '2/1/2016';
declare @enddate datetime = '1/1/2017';
select 
convert(date,DATEADD(dd, DATEDIFF(dd, 0, datefinalized), 0))  as Dates,
count(OrderID) as OrderCount
from orders 
where datefinalized between @startdate and @enddate
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, datefinalized), 0)
order by DATEADD(dd, DATEDIFF(dd, 0, datefinalized), 0) desc

问题是当我在单个SQL语句中组合这两个查询时。 LEFT JOIN 执行 20秒(!!!)。我尝试了一个giggles的子查询,并且在 13秒时它没有好多了:

如何有效地加入结果数据集?

提前感谢您的时间。

1 个答案:

答案 0 :(得分:1)

使用递归cte是生成一系列日期的最糟糕方法之一。使用堆叠cte much faster可以按需生成日期范围,而不是使用递归cte。

如果您要在多行或长时间内使用它,或者您将多次运行此类操作,那么最好只创建Dates或{{1} } table。

内存中只有152kb,你可以在一张桌子上有30年的日期,你可以像这样使用它:

Calendar

并像这样查询:

/* dates table */ 
declare @fromdate date = '20000101';
declare @years    int  = 30;
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
select top (datediff(day, @fromdate,dateadd(year,@years,@fromdate)))
    [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
into dbo.Dates
from n as deka cross join n as hecto cross join n as kilo 
               cross join n as tenK cross join n as hundredK
order by [Date];

create unique clustered index ix_dbo_Dates_date 
  on dbo.Dates([Date]);

数字和日历表参考:

如果您真的不想要日历表,可以使用堆叠的cte部分:

select
    d.[Date]
  , OrderCount = count(o.OrderID)
from dates d
  left join orders o
    on convert(date,o.OrderDate) = d.[Date]
group by d.[Date]
order by d.[Date] desc