二個SQL tuning例子(使用case)
減少對錶的掃描次數,將大大有利於執行的效率
例子1(低效):
select z.dept_name
from(select item_key,dept_name,min(b.begin_date) t1
from table1 a,table2 b
where activity_name='1';
and .....
group by ...) z,
(select item_key,min(b.begin_date) t2
from table1 a, table2 b
where activity_name='2'
and....
group by....) w,
(select item_key,max(b.begin_date) t3,min(b.end_date) t4
from table1 a, table2 b
where activity_name='3'
and.....
group by.....)Q
where z.item_key = w.item_key
and w.item_key = Q.item_key
例子1的(高效):
select dept_name,
max(T1) T1,
max(T2)T2
from (select dept_name,
(case
when activity_name = '1') then min(a.begin_date) else null end) t1,
(case
when activity_name='2') then min(a.end_date) else null end) t2
from table1 a, table2 b
where activity_name in('1','2');
and ......
and.....
說明:有些情況下,可以用case語句來提高效率。
例子二(高效)(case when 後面可接條件表示式,可以用於統計數量,效率還可以):
select t.dw,sum(case when exists(select 1 from table2 a
where a...= t....) and t...
then '1'
else '0' end ) 數量1,
sum(case when exists(select 1 from tabble 2 a
where a... = t...) and t...
then '1'
else '0' end) 數量2
from table t
where t.org_no like ''
and t.....
group by t.org_no
例子二(比前者低效)
select dw, sum(case when xm='數量1' then sl else 0 end)數量1,
sum(case when xm='數量2' then sl else 0 end)數量2
from (select t.org_no dw,'數量1' xm,count(*) sl
from table t
where t....
and t......
and exists(select 1 from table2 a
where a......)
group by t.org_no
union
select t.org_no dw, '數量2' xm,count(*) sl
from table t
where t.....
and exists(select 1 from table2 a
where a....)
group by t.org_no)
group by dw
[@more@]來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24214296/viewspace-1035165/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- SQL中的CASE WHEN使用SQL
- SQL Case when 的使用方法SQL
- sql loader使用例子SQL
- sql tuningSQL
- 使用sql tuning advisor最佳化sqlSQL
- SQL Case WhenSQL
- 【SQL】小CASESQL
- SQL Server遊標使用例子SQLServer
- sql tuning set/sql tuning advisor(待完善)SQL
- Sql Tuning Advisor 使用方法SQL
- SQL Tuning Advisor使用例項SQL
- sql tuning setSQL
- 熟悉SQL tuningSQL
- SQl CASE 語句的巢狀使用方式SQL巢狀
- 使用CASE表示式替代SQL Server中的動態SQLSQLServer
- SQL CASE 表示式SQL
- sql case語法和plsql case語法!SQL
- ORACLE SQL TUNING ADVISOR 使用方法OracleSQL
- sql tuning task和sql profileSQL
- Automatic SQL Tuning and SQL ProfilesSQL
- 【筆記】SQL tuning筆記SQL
- Oracle SQL Perfomance TuningOracleSQL
- sql語法case用法SQL
- 一個sql的行列轉置的例子SQL
- 使用SQL Profile及SQL Tuning Advisor固定執行計劃SQL
- SQL TUNING ADVISORSQL
- Automatic SQL Tuning 原理SQL
- sql tuning之變通SQL
- [原創]ORACLE SQL TUNING ADVISOR 使用方法OracleSQL
- Oracle case when改寫SQLOracleSQL
- 【SQL 學習】case 表示式SQL
- 轉 sql 中 case 的用法SQL
- PL/SQL Case when應用SQL
- sql case when, Exist ,group by ,聚合SQL
- SQL Server CASE WHEN ... THEN ... ELSE ... ENDSQLServer
- 在EM中使用SQL Tuning Advisor(SQL優化建議)優化SQLSQL優化
- 10個SQL技巧之二:使用遞迴SQL生成資料SQL遞迴
- SPA_SQL Performance Analyzer_SQL Tuning SetSQLORM