假设有个学生表,举个例子,简单期间就把成绩也放在这个表里面了
(学号,入学时间,班级号,性别,成绩 )
我想用一个SQL来查出,入学时间是98年,性别是男生,班级号是A班,B班成绩靠前的各10个人我本来是用二个SQL的,为了提高性能,希望能合到一个SQL里面
SELECT * From 学生表 where 入学时间=98年 and 性别=男 and 班级=A and rownum < 11 ord by 成绩 DESC
SELECT * From 学生表 where 入学时间=98年 and 性别=男 and 班级=B and rownum < 11 ord by 成绩 DESC能合为一个SQL吗?

解决方案 »

  1.   

    SELECT *
    FROM 
    (SELECT * From 学生表 where 入学时间=98年 and 性别=男 and 班级=A and rownum < 11 
    union all
    SELECT * From 学生表 where 入学时间=98年 and 性别=男 and 班级=B and rownum < 11 
    )A
    ORDER BY 成绩 DESC ;
      

  2.   


    select 学号, 班级, 成绩
      from (select a.*, rank() over(partition by 班级 order by 成绩 desc) 名次
              from (SELECT *
                      From 学生表
                     where 入学时间 = 98年
                       and 性别 = 男
                       and (班级 = A or 班级 = B)) a)
     where 名次 <= 10
      

  3.   

    SELECT * From 学生表 where 入学时间=98年 and 性别=男 and 班级=A and rownum < 11 ord by 成绩 DESC
    SELECT * From 学生表 where 入学时间=98年 and 性别=男 and 班级=B and rownum < 11 ord by 成绩 DESCselect * 
      from (
            select a.*, row_number()over(partition by 班级 order by 成绩 DESC) as rn 
              from  学生表 a
             where 入学时间=98年 and 性别=男 and 班级 in (A, B)
            )
     where rn <= 10
      

  4.   

    2楼 3楼均对,3楼效率要高一些,3楼用dense_rank()更准确一些。
      

  5.   

    rownum + order by 是oracle经典误区
    1楼的大大被楼主误导了2楼的应该可以select s.*, rownum from (
    SELECT * From 学生表
     where 入学时间=98年 and 性别=男 and 班级=A order by 成绩 DESC
    ) s where rownum<=10
    union all
    ...
      

  6.   

    假设有个学生表,举个例子,简单期间就把成绩也放在这个表里面了 
    (学号,入学时间,班级号,性别,成绩 ) 
    我想用一个SQL来查出,入学时间是98年,性别是男生,班级号是A班,B班成绩靠前的各10个人 我本来是用二个SQL的,为了提高性能,希望能合到一个SQL里面 
    SELECT * From 学生表 where 入学时间=98年 and 性别=男 and 班级=A and rownum < 11 ord by 成绩 DESC 
    SELECT * From 学生表 where 入学时间=98年 and 性别=男 and 班级=B and rownum < 11 ord by 成绩 DESC 能合为一个SQL吗?--sql server写法
    select t.* from 学生表 t where 入学时间='98年' and 性别='男' and 班级 in ('A','B') and 成绩 in
    (select top 10 成绩 from 学生表 where 入学时间='98年' and 性别='男' and 班级 in ('A','B') and 班级 = t.班级 order by 成绩 DESC )--oracle 写法
    select * from
    (
    select t.* , row_number() over(partition by 班级 order by 成绩 desc) px from 学生表 t where 入学时间='98年' and 性别='男' and 班级 in ('A','B')
    ) m
    where px <= 10