1. 程式人生 > >oracle復雜查詢是sql

oracle復雜查詢是sql

first ast 一個 分析 number 分組 val -m 復雜

一、over()分析函數

  分組查前幾條:select * from test t where (select count(*) from test a where t.type=a.type and t.scope>a.scope)<2;

  --rank()/dense_rank() over(partition by ...order by ...)
  select * from(select t.*,rank() over(partition by t.type order by t.scope ) a from TEST t) a where a.a<3

--dense_rank()分級 連續排序
select t.*,dense_rank() over(partition by t.type order by t.scope)a from test t
--rank()分級 跳躍排序
select t.*,rank() over(partition by t.type order by t.scope)a from test t

select * from Test t where 2>(select count(*) from Test a where t.type=a.type and t.scope>a.scope)
select t.* from Test t,(select a.type,max(a.scope) scope from TEST a group by a.type) d where t.type=d.type and t.scope=d.scope

--笛卡爾乘積
select * from Test t,Test a
select t.* from Test t,(select a.type,max(a.scope) maxscope,min(a.scope) minscope from TEST a group by a.type) d where t.type=d.type and t.scope=d.scope


  --
select t.*,d.maxscope-t.scope maxscope,t.scope-d.minscope minscope
from Test t,
(select a.type, max(a.scope) maxscope, min(a.scope) minscope
from TEST a
group by a.type) d
where t.type = d.type

--min()/max() over(partition by ...)
select t.*,
nvl(max(t.scope) over(partition by t.type), 0) - t.scope maxscope,
t.scope - nvl(min(t.scope) over(partition by t.type), 0) minscope
from test t

--lead()/lag() over(partition by ... order by ...)
select t.*,lead(t.scope,1,0)over(partition by t.type order by t.scope) a--同組後一個
from test t
select t.*,lag(t.scope,1,0)over(partition by t.type order by t.scope) a--同組前一個
from test t



select t.*,
first_value(t.scope) over(partition by t.type) first_sal,
last_value(t.scope) over(partition by t.type) last_sal,
sum(t.scope) over(partition by t.type) sum_sal,
avg(t.scope) over(partition by t.type) avg_sal,
count(t.scope) over(partition by t.type) count_num,
row_number() over(partition by t.type order by t.scope) row_num
from test t


--註:帶order by子句的方法說明在使用該方法的時候必須要帶order by


oracle復雜查詢是sql