一个SQL语句的优化(sqlserver)

时间:2022-08-11 10:01:59

最早的写法:

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) as 票数 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) as 票数 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语句理解有误!!!