----------一条SQL语句求解---------
表TBL 
NAME  GRADE  
  张三  100
  张三  100
  张三  80
  张三  60
  张三  60
  李四  80
  李四  60
  李四  60
  王五  60
  ...
  ... 
  求:统计GRADE为100时人数,统计GRADE为80时人数,统计GRADE为60时人数
  限制:1:每个人只允许参与一次统计,如张三2条记录GRADE为100但只统计一条
        2:若张三在GRADE为100被统计,则在GRADE为80和60时都不被统计(GRADE为80和60时不考虑张三)。

解决方案 »

  1.   

    select count(1)
      from (select distinct name, grade from tbl where grade = 100);
    select count(1)
      from (select distinct name, grade
              from tbl a
             where a.grade = 80
               and not exists (select name
                      from tbl b
                     where grade = 100
                       and a.name = b.name));
    select count(1)
      from (select distinct name, grade
              from tbl a
             where a.grade = 60
               and not exists (select name
                      from tbl b
                     where grade in (100,80)
                       and a.name = b.name));
      

  2.   

       补充一句,这其实是我将SQL简化后要求的算法,中间过程已经很复杂,表数据超过千万,
       请高手尽量用效率高的算法,谢过
     再次感谢楼上
      

  3.   

    select grade,count(1) num
    from 
    (select name,max(grade) grade from tbl group by name) A
    group by grade;
      

  4.   

    with tbl as (
        select 'a' name ,100 grade from dual
        union
        select 'a' name ,80 grade from dual
        union
        select 'b' name ,60 grade from dual
        
    )select sum(case a.GRADE when 100 then 1 else 0 end) ,sum(case a.GRADE when 80 then 1 else 0 end),sum(case a.GRADE when 60 then 1 else 0 end)
    from
    (select max(GRADE) GRADE,NAME
       from tbl
      group by NAME) a