日期:2014-05-17  浏览次数:20544 次

SQL sum(decimal)速度慢的问题
首先描述
typeid 是商品的大分类
bumenid 是公司某一个部门的ID
begin,end 查询的是订单的时间

view_ordersaleproductdetail[视图] 里面是存放订单的详细详细,包括产品名称,数量,价格等等
tb_ordersale 是订单表

tb_ordersale.id 与 tb_ordersaleproduct.ordersaleid 是外键关系

tb_f_c_profit 是利润表,ledgerID列和tb_f_ledger.ID是外键关系
              
---------------------查询测试语句

declare @begin datetime,@end datetime,@typeid int,@bumenid int
set @begin='2013-3-1'
set @end='2013-4-10'
set @bumenid=2
set @typeid=60
select isnull(sum(profit),0) as lirun 
from
(
SELECT      pf.Profit, ospd.orderid, ospd.Type, ospd.typeid, ospd.Sort, ospd.sortid, ospd.[Group], ospd.groupid, ospd.Brand, ospd.brandid, 
                      ospd.ProductID, ospd.Model, ospd.Quantity, ospd.Price, ospd.BuMenID, ospd.OrderTime
FROM         dbo.View_OrderSaleProductDetail1 AS ospd INNER JOIN
                      dbo.tb_OrderSale AS os ON os.ID = ospd.ordersaleid LEFT OUTER JOIN
                      dbo.tb_f_Ledger AS l ON l.OrderID = os.OrderID AND l.OperationID = 1 LEFT OUTER JOIN
                      dbo.tb_f_c_Profit AS pf ON pf.LedgerID = l.ID AND pf.ProductID = ospd.ProductID
)
as
aaa
where 
 ordertime between @begin and @end   and   bumenid=@bumenid    and  typeid=@typeid


我想得到的是 某个部门,某个大分类在制定时间段内的销售统计数据【销售数量,利润,总金额】

但是非常奇怪的是,现在表里面只有6000条数据,但是非常慢
能到14秒才加载出数据。
而且,如果
我把 isnull(sum(profit),0) as lirun  换了就很快

或者是  我把where 中的bumenid=@bumenid  限制去掉或是
and  typeid=@typeid 其中之一去掉就很快...

为啥啊。这个???请大家分析下啊,


------解决方案--------------------
你尽量不要用视图,因为:
1、表可能重复了几次。
2、查询了不必要的列,而这些列没用合理利用到索引。

另外,多考虑能否加多点where条件,如果没有足够的筛选条件,依旧是索引、聚集索引扫描
------解决方案--------------------

我的建议是
第一 isnull(sum(profit),0)  这句话的意义不是很大,除非你设置了sum(null) 等于null,系统默认是忽略null的,可以直接使用 sum(profit)。
第二 这个和版主回答的是一样的,先把符合条件的记录筛选出来,然后再进行关联。
第三 在 SELECT      pf.Profit, ospd.orderid, ospd.Type, ospd.typeid, ospd.Sort, ospd.sortid, ospd.[Group], ospd.groupid, ospd.Brand, ospd.brandid, 
                      ospd.ProductID, ospd.Model, ospd.Quantity, ospd.Price, ospd.BuMenID, ospd.OrderTime
中不要返回那么多的列,只返回你需要的列。

引用:
首先描述
typeid 是商品的大分类
bumenid