T-SQL Too Many加入全表

时间:2015-12-15 16:13:14

标签: sql sql-server tsql

我创建了一个运行的查询...实际上只需要9秒就可以自行运行。但是......当我尝试将它用作左或右连接语句中的主表时,会导致该查询失败(超时)。

我相信它是因为我在桌子上打了14次左右(表格中的500k行)来比较某些行。我相信有一种方法可以将其合并为2个全表扫描......但我不知道如何。

以下是我如何检查两种情况的示例...我这样做了大约4-5次。

谢谢!

left join

--SUM THE DURATION OF LUNCHES DURING PTO
(SELECT  o.employee,  convert(date, o.start_time) as createdate,


            SUM(DATEDIFF (
                       minute,
                       CASE WHEN S.START_time  < O.START_time  THEN O.START_time  
                            ELSE S.START_time 
                       END, 
                       CASE WHEN S.STOP_time   > O.STOP_time   THEN O.STOP_time
                            ELSE S.STOP_time  
                       END
                     )) as unplanned_superstate

 FROM table1 O  -- LUNCH CONTAINERS
 JOIN table1 S  -- PTO CONTAINERS
 ON O.Employee = S.Employee
 AND s.START_time <= o.STOP_time
 AND S.STOP_time >= o.START_time  

 WHERE 
 O.code IN ('LUNCH')
 AND S.code  IN  ('CODE1','CODE2','CODE3','CODE4')

 group by o.employee, convert(date, o.start_time)
 ) ul

 on ul.employee = segments.employee and segments.createdate = ul.createdate


left join


--SUM THE DURATION OF LUNCHES DURING SHIFT
   (SELECT  o.employee,  convert(date, o.start_time) as createdate,       
             SUM(DATEDIFF (
                       minute,
                       CASE WHEN S.START_time  < O.START_time  THEN O.START_time  
                            ELSE S.START_time 
                       END, 
                       CASE WHEN S.STOP_time   > O.STOP_time   THEN O.STOP_time
                            ELSE S.STOP_time  
                       END
                     )) shift_superstate

   FROM table1 O  -- LUNCH CONTAINERS
   JOIN table1 S  -- SHIFT CONTAINERS
 ON O.Employee = S.Employee
 AND S.START_time <= O.STOP_time
 AND S.STOP_time >= o.START_time 

WHERE 
  O.code = 'LUNCH'
AND S.code  IN ('SHIFT')

group by o.employee, convert(date, o.start_time)
) ul2

on ul2.employee = segments.employee and segments.createdate = ul2.createdate

0 个答案:

没有答案