1. 程式人生 > >怎樣用SQL語句實現查詢一列中的第N大值?

怎樣用SQL語句實現查詢一列中的第N大值?

答:select * from (select * from 表 order by 列名 Desc) where Rownum <= N
Minus
select * from (select * from 表 order by 列名 Desc) where Rownum <= N-1;


客戶表a(id name address) 登陸流水錶b(id time) 購物流水錶c(id time productid productnum)
 
 1.求每個客戶的最新登陸時間time姓名name客戶id
    select a.ida.named.time as time
    from a left join (select idmax(time) as time from b group by id) d
    on a.id =d.id ;
 2.查最新登陸並且已經購買商品的客戶idname登陸的時間time(一條sql語句)
    select a.ida.named.time as time
    from a(select idmax(time) as time from b group by id) d
    where a.id =d.id
    and exists (select * from c where id = a.id);

一個表student中有班級classid學號id成績grade
 1.計算各個班的平均成績
    select classid avg(grade)
    from student
    group by classid;
 2.查詢比該班平均成績高的學生的班級classid學號id成績grade
    select a.classida.ida.grade
    from student a
    where a.grade >(select avg(grade) from student where classid = a.classid);