我已经在下面的查询中创建了此查询,该查询正在计算每个日期之前的总和。这个查询给我确切的结果,但是它具有很大的数据。我如何加快或优化它?
IF OBJECT_ID('TEMPDB..#temp')IS NOT NULL
DROP TABLE #temp
IF OBJECT_ID('TEMPDB..#temp1')IS NOT NULL
DROP TABLE #temp1
Declare @DateFrom DateTime
Set @DateFrom = CONVERT(DATE,DATEADD(D,-datepart(d,getdate())+1,DATEADD(M,-1,GETDATE())))
Declare @DateTo DateTime
Set @DateTo = CONVERT(DATE,DATEADD(D,-DATEPART(D,getdate()),GETDATE()))
Select
Date
,[Item No_]
,case when Sum(ILE.Quantity)>0 and [Posting Date]=Date then Sum(ILE.Quantity) else 0 end AS [In Quantity],
case when Sum(ILE.Quantity)<0 and [Posting Date]=Date then Sum(ILE.Quantity) else 0 end AS [Out Quantity],
(Sum(ILE.Quantity))Closing
into #temp
from Calender C left Join [Snowman Logistics Limited$Item Ledger Entry]ILE on Cast(ILE.[Posting Date]as date)<=C.Date
Group by Date,[Item No_],[Posting Date]
Select Date,[Item No_]
,SUm([In Quantity])[In Quantity],Sum([Out Quantity])[Out Quantity],Sum(Closing)Closing from #temp where Date Between @DateFrom and @DateFrom
group by Date,[Item No_]
您可以尝试:
INNER JOIN
,即使在[dates]-[items]
表中指定时间段内没有针对它们的条目,如果仍然需要[Snowman Logistics Limited$Item Ledger Entry]
,您可以稍后进行; [Posting Date]
强制转换为日期-如果它是字符串而不是日期/日期时间类型,则应更改它以便在计算过程中跳过显式(或隐式)强制转换1
正常并且可以使用INNER JOIN
,则可以尝试创建indexed view并预先计算初始查询在您的第一个查询中,您将记录按[Posting Date]
分组,在第二个查询中,您将记录重新分组,但不包括它-您无法统一查询吗?
Select
Date
,[Item No_]
,case when Sum(ILE.Quantity)>0 and [Posting Date]=Date then Sum(ILE.Quantity) else 0 end AS [In Quantity],
case when Sum(ILE.Quantity)<0 and [Posting Date]=Date then Sum(ILE.Quantity) else 0 end AS [Out Quantity],
(Sum(ILE.Quantity))Closing
into #temp
from Calender C
left Join [Snowman Logistics Limited$Item Ledger Entry]ILE
on Cast(ILE.[Posting Date]as date) <= C.Date
where Date Between @DateFrom and @DateFrom
Group by Date,[Item No_]
取决于表的方式以及创建wide
可以提高性能的列的类型-这些类型的索引将仅包含您在查询中使用的列,因此数据较少将被读取(较少的IO)。