有人可以帮助我提高SQL查询的效率吗?

时间:2016-08-10 18:22:12

标签: sql-server

{{1}}

这需要永远运行,任何想法?

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT 
    datepart(qq, o.created_date),
    count(DISTINCT o.order_id),
    sum(o.order_margin)
FROM
    orders o
INNER JOIN 
    emailsegment e ON e.account_id = o.account_id AND e.segment = 'H'
WHERE  
    o.created_date >= '2016-01-01'
    AND o.order_status = 'Shipped'
GROUP BY 
    datepart(qq, o.created_date)
ORDER BY 
    datepart(qq, o.created_date) 

答案 1 :(得分:0)

只是几个疯狂的猜测:

  1. 查询后返回多少条记录以及运行多长时间?
  2. SELECT e.account_id FROM emailsegment e WHERE e.segment = 'H';

    使用account_id列上的过滤器在segment上创建索引可能会有所帮助。

    CREATE INDEX ix_account_id_emailsegment ON emailsegment(account_id)
    WHERE segment = 'H'
    

    CREATE INDEX ix_segment_emailsegment ON emailsegment(segment)
    INCLUDE (account_id)
    
    1. 根据哪个过滤记录数量较小created_date >= '1/1/2016'o.account_id IN (o.order_status = 'Shipped',该列必须是索引中的第一列。会说它会created_date然后你必须创建一个索引,如:
    2. CREATE INDEX ix_created_date_orders on orders(created_date, account_id, order_id) INCLUDE (order_margin) WHERE order_status = 'Shipped';

      如果您的列order_id是聚簇索引,那么您没有将其包含在索引中。

      1. 您可以尝试在您的子查询中添加单词DISTINCT。不确定这是否有帮助。