一个SQL语句的优化(sqlserver)
Posted Timeless
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个SQL语句的优化(sqlserver)相关的知识,希望对你有一定的参考价值。
最早的写法:
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=N‘xx‘ 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=N‘xx‘ 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)的主要内容,如果未能解决你的问题,请参考以下文章