id       班级        成绩
1          a              23
2          b              33
3          c               43
4          a               53
6          b               55
7          c               33请教1:组外排序,以组为单位排序,并且给序号,以班级为分组
排成
序号     id       班级        成绩
   1        1           a             23
   1        4           a             53
   2        2           b             33
   2        7           b             55
   3        3           c             43
   3        6           c             33请教2:组内排序
排成
序号     id       班级        成绩
   1        1           a             23
   2        4           a             53
   1        2           b             33
   2        7           b             55
   1        6           c             33
   2        3           c             43
  请教这两种的sql应该怎么写呢?
oralce和mysql
因为oracle和些函数可以实现,但是mysql确不可以,所以想分别请教这两种需求的两写法

解决方案 »

  1.   

    只会oracle :
    第一种:
    with tmp(id,  班级  , 成绩)as
    (select '1','a','23' from dual union all
    select '2','b','33' from dual union all
    select '3','c','43' from dual union all
    select '4','a','53' from dual union all
    select '6','b','55' from dual union all
    select '7','c','33' from dual)
    select sum(r)over(order by rownum) as 序号,id,班级,成绩 from 
    (select t.*,
           case
             when lag(班级) over(partition by 班级 order by 成绩) is null then
              1
             else
              0
           end r
      from tmp t)第二种:
    with tmp(id,  班级  , 成绩)as
    (select '1','a','23' from dual union all
    select '2','b','33' from dual union all
    select '3','c','43' from dual union all
    select '4','a','53' from dual union all
    select '6','b','55' from dual union all
    select '7','c','33' from dual)
    select row_number() over(partition by 班级 order by 成绩) as 序号, t.*
      from tmp t
      

  2.   

    with tmp(id,  class  , grade)as
    (select '1','a','23' from dual union all
    select '2','b','33' from dual union all
    select '3','c','43' from dual union all
    select '4','a','53' from dual union all
    select '6','b','55' from dual union all
    select '7','c','33' from dual)
    select subtmp.xuhao,t.*
    from (select class,row_number() over(order by class) xuhao
    from tmp group by class) subtmp,
    tmp t
    where t.class=subtmp.class
    order by t.class,t.grade 
      

  3.   

    with tmp(id,class,grade)as
    (select '1','a','23' from dual union all
    select '2','b','33' from dual union all
    select '3','c','43' from dual union all
    select '4','a','53' from dual union all
    select '6','b','55' from dual union all
    select '7','c','33' from dual)
    select dense_rank() over(partition by class order by grade),dense_rank() over(order by class),t1.* from tmp t1 order by class,grade;