子查询,TOP_N,分页,行转列

1.子查询

sql中查询是可以嵌套的。一个查询可以作为另外一个查询的条件、表。

SELECT select_list

FROM   table

WHERE  expr operator

       (SELECT    select_list

            FROM  table);

 

理解子查询的关键在于把子查询当作一张表来看待。外层的语句可以把内嵌的子查询返回的结果当成一张表使用。子查询可以作为一个虚表被使用。

子查询要用括号括起来

将子查询放在比较运算符的右边(增强可读性)

子查询根据其返回结果可以分为单行子查询和多行子查询。

1)单行子查询

当子查询有单行时,可以取单行中的一个字段形成单个值用于条件比较。

 1 -- 查询雇员其薪资在雇员平均薪资以上
 2 
 3 -- [1] 查询员工的平均薪资
 4 
 5 selectavg(e.sal) "AVGSAL"
 6 
 7 from emp e
 8 
 9  
10 
11 --[2] 查询满足条件的雇员
12 
13 select *
14 
15 from emp e
16 
17 where e.sal > (selectavg(e.sal) "AVGSAL" from emp e)

2) 多行子查询

 1 -- 查在雇员中有哪些人是管理者
 2 
 3 --【1】查询管理者
 4 
 5 selectdistinct e.mgr
 6 
 7 from emp e
 8 
 9 where e.mgr isnotnull
10 
11  
12 
13 --【2】查询指定列表的信息 in
14 
15 select e.*
16 
17 from emp e
18 
19 where e.empno in (selectdistinct e.mgr
20 
21 from emp e
22 
23 where e.mgr isnotnull)

多行子查询返回的结果可以作为表使用,通常结合in、some/any、all、exists。

3)    From后的子查询

子查询可以作为一张续表用于from后。

扫描二维码关注公众号,回复: 6249883 查看本文章
-- 每个部门平均薪水的等级

--【1】部门的平均薪资

select e.deptno,avg(e.sal) "AVGSAL"

from emp e

groupby e.deptno

 

--【2】求等级

select vt0.deptno,vt0.avgsal,sg.grade

from (select e.deptno,avg(e.sal) "AVGSAL"

from emp e

groupby e.deptno) VT0,salgrade sg

where vt0.avgsal between sg.losal and sg.hisal
-- 99 join on

select vt0.deptno,vt0.avgsal,sg.grade

from (select e.deptno,avg(e.sal) "AVGSAL"

from emp e

groupby e.deptno) VT0 join salgrade sg on vt0.avgsal between sg.losal and sg.hisal

2. TOP-N

把select得到的数据集提取前n条数。

rownum:表示对查询的数据集记录的编号,从1开始。

-- 查询前10名雇员

select e.*,rownum

from emp e

whererownum<= 10

rownum和order-by

-- 查询按照薪资降序,前10名雇员

select e.*,rownum

from emp e

whererownum<= 10

orderby e.sal desc

总结

[1] order by 一定在整个结果集出现后才执行。

[2] rownum 在结果集出现后才有编号。

。。。-> select -> rownum -> order by

-- 查询按照薪资降序,前10名雇员

select vt0.*,rownum

from (select e.*

from emp e

orderby e.sal desc) VT0

whererownum<= 10

3. 分页

-- 求查询6-10号的雇员

select vt0.*

from (select e.*,rownum "RN"

from emp e

whererownum<= 10) VT0

where vt0.rn >= 6

求page=n,pagesize=size的数据

=>[(n-1)*size+1,n*size]

select vt0.*

from (select t.*,rownum “RN”

from table t

where rownum <= n*size) VT0

where vt0.rn >= (n-1)*size+1

4.   行转列

 

4.1得到类似下面的结果

姓名语文数学英语

张三    78    88    98

王五    89    56    89

 1 select ts.name,
 2 
 3 sum(decode(ts.subject,'语文',ts.score)) "语文",
 4 
 5 sum(decode(ts.subject,'数学',ts.score)) "数学",
 6 
 7 sum(decode(ts.subject,'英语',ts.score)) "英语"
 8 
 9 from test_score ts
10 
11 groupby ts.name

猜你喜欢

转载自www.cnblogs.com/qq2267711589/p/10877612.html