码迷,mamicode.com
首页 > 数据库 > 详细

一个SQL语句的优化(sqlserver)

时间:2018-08-04 16:42:12      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:优化   inner   语句   nio   rom   class   ike   between   最大的   

最早的写法:

WITH T AS
(SELECT case when Col1 IS NULL OR Col1=N‘‘ then Col2 else Col1 end as Code,case when Col1 IS NULL OR Col1=N‘‘ then 1 else 0 end as Flag FROM YM  WHERE Col_076 BETWEEN 2018-07-25 AND 2018-08-03 AND Col_478=Nxx AND Col_346 LIKE N%dd%),
D AS (SELECT Code,province,city  FROM Adds)
SELECT province AS 省,city as 市,COUNT(1) 票数 FROM 
(SELECT A.DR_250 as province,A.DR_251 as city FROM T INNER JOIN TB AS A ON A.DR_203=T.Code WHERE T.Flag=0
 UNION ALL
 SELECT D.province,D.city FROM T INNER JOIN D ON D.Code=T.Code WHERE T.Flag=1
 UNION ALL
 SELECT ‘‘ AS province,‘‘ AS city FROM T WHERE Code IS NULL OR Code=N‘‘) AS S 
GROUP BY province,city;

 

最新的写法:

SELECT case when Col1 IS NULL OR Col1=N‘‘ then Col2 else Col1 end as Code,case when Col1 IS NULL OR Col1=N‘‘ then 1 else 0 end as Flag into #T FROM YM WHERE Col_076 BETWEEN 2018-07-25 AND 2018-08-03 AND Col_478=Nxx AND Col_346 LIKE N%dd%;
SELECT Code,province,city into #D  FROM Adds;
SELECT province AS 省,city as 市,COUNT(1) 票数 FROM 
(SELECT A.DR_250 as province,A.DR_251 as city FROM #T INNER JOIN TB AS A ON A.DR_203=#T.Code WHERE #T.Flag=0
UNION ALL
SELECT #D.province,#D.city FROM #T INNER JOIN #D ON #D.Code=#T.Code WHERE #T.Flag=1
UNION ALL
SELECT ‘‘ AS province,‘‘ AS city FROM #T WHERE Code IS NULL OR Code=N‘‘) AS S GROUP BY province,city;
DROP table #T;
DROP table #D;

新的写法比原始写法性能高出太多(原语句执行会超时),最大的原因是对with语句理解有误!!!

一个SQL语句的优化(sqlserver)

标签:优化   inner   语句   nio   rom   class   ike   between   最大的   

原文地址:https://www.cnblogs.com/kingge/p/9418993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!