如何使用聚合加速查询?

时间:2013-06-06 19:02:13

标签: sql sql-server aggregate

如果在select部分中使用了多个聚合,我有以下查询似乎运行得很慢。有没有办法优化这个?

查询返回168行并需要1秒才能完成,但是当一些用户一次加载页面并且原始查询有更多聚合时,这会使查询增加秒数,从而陷入困境。

*****这里更新是一个更简单的查询**

Select 
    gocm.CustomerID,
    sum(DISTINCT o.OrderTotal) as TotalOfOrders
from GroupOrder_Customer_Mapping gocm
    Left Join [Order] o on o.CreatedForCustomerID = gocm.customerid and o.grouporderid = 8254
where gocm.grouporderid = 8254
    group by gocm.CustomerID, invitePath
    order by invitepath 

执行计划

enter image description here

返回以下数据(示例结果) enter image description here

2 个答案:

答案 0 :(得分:1)

这可能对你有所帮助 -

SELECT 
      gocm.CustomerID
    , o.TotalOfOrders 
FROM (
    SELECT DISTINCT gocm.CustomerID, invitePath
    FROM dbo.GroupOrder_Customer_Mapping gocm
    WHERE gocm.grouporderid = 8254
) gocm 
LEFT JOIN (
    SELECT 
          o.CreatedForCustomerID
        , TotalOfOrders = SUM(DISTINCT o.OrderTotal) 
    FROM dbo.[Order] o
    WHERE o.grouporderid = 8254
    GROUP BY o.CreatedForCustomerID
) o ON o.CreatedForCustomerID = gocm.customerid 
ORDER BY invitepath 

答案 1 :(得分:0)

如果数据未经常更新,您可能会考虑使用indexed view