使用except除外查询时间过长

时间:2013-02-12 17:23:06

标签: sql

有没有更短的方式...... ??

SELECT clid, cldoel, clanker, clprefix, clleerlijn, f1, f2, f3, f4 FROM Clusters  
WHERE clleerlijn like 'WJNLLUI%'   AND (f3 IS NOT NULL  OR f4 IS NOT NULL )
AND clid in(
Select agClid FROM agenda2 as a JOIN evaluaties2 as e ON a.agclid = e.evalclid and agLkrid = evallkrid 
WHERE (agSchoolid='18' and agDatum >=   '2013/01/01' and agDatum <=   '2013/02/12')
GROUP BY agClid
except
(SELECT agClid
FROM agenda2 as a 
    JOIN evaluaties2 as e 
        ON a.agclid = e.evalclid and agLkrid = evallkrid 
WHERE agSchoolid='18' 
    and agLkrid in (1,2932,2935) 
    and agDatum >= '2013/01/01' 
    and agDatum <= '2013/02/12' 
    AND evalWaarde = 3
GROUP BY agclid
HAVING COUNT(DISTINCT agLkrid) = 3)
)

1 个答案:

答案 0 :(得分:0)

由于两次使用相同的CTE,只有一点点,但更好的可读性:

WITH cte(clid) As (
  Select agClid FROM agenda2 as a JOIN evaluaties2 as e ON a.agclid = e.evalclid and agLkrid = evallkrid 
  WHERE (agSchoolid='18' and agDatum >= '2013/01/01' and agDatum <= '2013/02/12')
)
SELECT clid, cldoel, clanker, clprefix, clleerlijn, f1, f2, f3, f4 FROM Clusters  
WHERE clleerlijn like 'WJNLLUI%' AND (f3 IS NOT NULL  OR f4 IS NOT NULL )
AND clid in(
  SELECT DISTINCT agClid FROM cte
  except
  (SELECT agClid FROM cte WHERE agLkrid in (1,2932,2935) AND evalWaarde = 3
   GROUP BY agclid
   HAVING COUNT(DISTINCT agLkrid) = 3
  )
)

我还将第一个GROUP BY更改为SELECT DISTINCT。

如果您正在寻找更高效的解决方案,那将无济于事。不会更快地评估重写的SQL语句。