某日同事丢给我一个看上去复杂的查询(实际就设计两张表,套来套去)说只是换了日期条件,但一个查询5秒出数据,一个根本查不出来。现在整理下解决过程,及涉及的知识点。 若有不正之处,请多多谅解并欢迎批评指正,不甚感激。 请尊重作者劳动成果,转载请标明原文链接: http: ...
某日同事丢给我一个看上去复杂的查询(实际就设计两张表,套来套去)说只是换了日期条件,但一个查询5秒出数据,一个根本查不出来。现在整理下解决过程,及涉及的知识点。
若有不正之处,请多多谅解并欢迎批评指正,不甚感激。
请尊重作者劳动成果,转载请标明原文链接:
http://www.cnblogs.com/zzry/p/5857751.html
一.问题描述
环境:sqlserver 2008r2
现象:
查询设计到
ODS_TABLE_A 每日数据700万现在总计60多亿。 已建立索引+分区
MID_TABLE_B 每日数据20万 总计3000万。 已建立索引未分区
当etldate为 '2016-08-12' 及以前的时间时,本查询5秒出数据,
当etldate为 '2016-08-16' 及以后的时间时,本查询出不来数据。
贴上问题sql:做过数据字段处理,针对本篇主题注意点放在查询因为日期的选择不同导致查询时间变的超级慢,而不是改变sql写法比如用临时表,强制索引上。
----------《代码开始》
select COUNT(distinct(case when COL_USERID3 is null then COL_USERID6 end)) as 'aa',COUNT(distinct(case when COL_USERID3 is null and COL_USERID7 is not null then COL_USERID6 end)) as 'bb',COUNT(distinct(case when COL_USERID3 is not null then COL_USERID6 end)) as 'cc',COUNT(distinct(case when COL_USERID3 is not null and COL_USERID7 is not null then COL_USERID6 end)) as 'dd',SUM(case when COL_USERID3 IS not null then ee end) as 'ee'from( select c.COL_USERID3,c.ee,g.COL_USERID6 from ( select b.COL_USERID2 as COL_USERID3,COUNT(b.COL_USERID2) as ee from ( select COL_USERID as COL_USERID1,min(EventTime) as time1 from ODS_TABLE_A where EtlDate = '2016-08-12' and colid LIKE 'heihei%' group by COL_USERID )as a join ( select COL_USERID as COL_USERID2,eventtime as time2 from ODS_TABLE_A where EtlDate = '2016-08-12' and ItemId = '1111111111101' and colid like 'haha-%' and colid not like 'haha-skill%' and colid not like 'haha-fine%' )as b on a.COL_USERID1 = b.COL_USERID2 and a.time1 > b.time2 group by b.COL_USERID2 )as c right join ( select DISTINCT d.COL_USERID4 as COL_USERID6 from ( select distinct COL_USERID as COL_USERID4 from MID_TABLE_B where etldate = '2016-08-12' )as d join ( select COL_USERID AS COL_USERID5 from ODS_TABLE_A where EtlDate = '2016-08-12' and colid LIKE 'heihei%' )as f on d.COL_USERID4 = f.COL_USERID5 )as g on c.COL_USERID3 = g.COL_USERID6)as ileft join( select COL_USERID as COL_USERID7 from MID_TABLE_B where EtlDate = '2016-08-12' and IsTodayPay = '1')as hon i.COL_USERID6 = h.COL_USERID7
原标题:sql调优
关键词:sql
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。