左连接在同一张桌子上 - 花了太长时间

时间:2017-07-22 06:42:33

标签: sql sql-server

此查询需要6-7个小时,有什么方法可以提升性能。

()

2 个答案:

答案 0 :(得分:0)

尝试在进行加入之前过滤数据,如下所示:

with TABLE_DATA as    
(    
select  CIF_KEY ,date, sum(cur_book_bal)cur_book_bal from table1  where Date in ('30-JUN-2014','30-juN-2015','30-JUNE-2016','30-JUNE-17')    
group by CIF_KEY,date    
)    
SELECT  INV1.cur_book_bal ,inv2.cur_book_bal,INV3.CUR_BOOK_BAL,INV4.CUR_BOOK_BAL      
from TABLE_DATA inv1     
left  join TABLE_DATA inv2    
on inv1.CIF_KEY= inv2.CIF_KEY    
left join TABLE_DATA inv3    
on inv1.CIF_KEY= inv3.CIF_KEY    
left  join TABLE_DATA inv4    
on inv1.CIF_KEY= inv4.cif_key    

where inv1.date = '30-JUN-2014' and inv2.date = '30-juN-2015' AND INV3.dATE = '30-JUNE-2016' AND INV4.DATE = '30-JUNE-17'

答案 1 :(得分:0)

编写此查询的最佳方法是使用条件聚合。我很确定这会得到你想要的结果:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  
  
<div class="main-container <?php print $container_class; ?>">
<div class="top-div row" style=" width:100%;background-color: #676767; font-weight:bold; color:white;">
<div class="row" style="text-align:center;">
<div class="col-md-4"> text </div>
<div class="col-md-4"> text </div>
<div class="col-md-4"> text</div>
</div> 
</div>

使用SELECT SUM(CASE WHEN date = '2014-06-30' THEN curr_book_bal else 0 end), SUM(CASE WHEN date = '2015-06-30' THEN curr_book_bal else 0 end), SUM(CASE WHEN date = '2016-06-30' THEN curr_book_bal else 0 end), SUM(CASE WHEN date = '2017-06-30' THEN curr_book_bal else 0 end), FROM table1 inv1 WHERE date in ('2014-06-30', '2015-06-30', '2016-06-30', '2017-06-30'); 上的索引,这应该是非常快速和准确的。

请注意使用标准日期格式。在查询中编写日期常量时,强烈建议这样做。