多个左连接的替代方法

时间:2017-09-25 10:07:45

标签: sql oracle

我有以下查询来计算路线销售额

SELECT DISTINCT q.sales_route, 
                y.yesterday, 
                t.today 
FROM   tblquotesnew q 
       left join (SELECT tblquotesnew.sales_route, 
                         Count(tblquotesnew.sales_route) AS Yesterday 
                  FROM   tblquotesnew 
                  WHERE  tblquotesnew.date_sent_to_registrations = 
                         Trunc(SYSDATE - 1) 
                         AND sales_route IS NOT NULL 
                  GROUP  BY tblquotesnew.sales_route) y 
              ON q.sales_route = y.sales_route 
       left join (SELECT tblquotesnew.sales_route, 
                         Count(tblquotesnew.sales_route) AS Today 
                  FROM   tblquotesnew 
                  WHERE  tblquotesnew.date_sent_to_registrations = 
                         Trunc(SYSDATE) 
                         AND sales_route IS NOT NULL 
                  GROUP  BY tblquotesnew.sales_route) t 
              ON q.sales_route = t.sales_route 

然后我有6个其他左连接来计算当前和上周,月和年。

这种方法确实有效,但我想知道这是否更有效(就代码行而言)将这些数据整合在一起的方式?

2 个答案:

答案 0 :(得分:4)

我认为你只需要条件聚合:

select q.sales_route, 
       sum(case when q.date_sent_to_registrations = trunc(SYSDATE - 1)
                then 1 else 0
             end) as yesterday,
       sum(case when q.date_sent_to_registrations = trunc(SYSDATE)
                then 1 else 0
             end) as today
from tblquotesnew q 
group by sales_route

答案 1 :(得分:1)

您可以使用条件聚合

SELECT sales_route, 
            sum(CASE WHEN date_sent_to_registrations = Trunc(SYSDATE) 
                          AND sales_route IS NOT NULL 
                     THEN 1 ELSE 0 END) today, 
            sum(CASE WHEN date_sent_to_registrations = Trunc(SYSDATE - 1) 
                          AND sales_route IS NOT NULL 
                     THEN 1 ELSE 0 END) yesterday 
FROM   tblquotesnew 
GROUP BY sales_route

条件聚合导致对表的一次顺序扫描,在许多情况下可能没问题。另一种解决方案是使用SELECT后面的子查询,有时可能是more efficient。例如,如果您访问小的子选择数据,则可以创建索引以支持它。