假设我有个表T, 里面的样本数据如下:
student       school
--------------------
学生1 初中1
学生1 高中1
学生1 大学1
学生2 高中2
学生2 大学2
学生3 高中1
学生3 大学2
学生4 高中1
学生5 大学2我想从表T里面找出同时满足下面条件的数据:
cond1:上过多个学校的学生的记录,这样 学生4 和 学生5 不满足条件
cond2:上过 高中1 的学生的数据 , 这样 就排除 学生3 的数据了总之,我期望的结果是:
student       school
--------------------
学生1 初中1
学生1 高中1
学生1 大学1
学生3 高中1
学生3 大学2
 

解决方案 »

  1.   


    cond1条件的sql如下:
    select student,school,count(1) from t group by studnet,school having count(1)>1;
      

  2.   

    晕,将lz的条件理解为二个sql了,lz的第二个条件应该是排除学生二吧。我再写一个,等会
      

  3.   


    create table t(student varchar2(8),school varchar2(8));
    select * from t;
    student      school
    --------------------
    学生1 初中1
    学生1 高中1
    学生1 大学1
    学生2 高中2
    学生2 大学2
    学生3 高中1
    学生3 大学2
    学生4 高中1
    学生5 大学2 
    select *
      from t
     where student in
           (select student
              from t
             where student in
                   (select student from t group by student having count(1) > 1)
               and school = '高中1');
        STUDENT SCHOOL
    1 学生1 初中1
    2 学生1 高中1
    3 学生1 大学1
    4 学生3 高中1
    5 学生3 大学2
      

  4.   


    --还可以这样写
    select *
      from t
     where student in (select student
                         from t t1
                        where exists (select 1
                                 from t t2
                                where t1.student = t2.student
                                  and t2.school = '高中1')
                        group by student
                       having count(1) > 1)
    --运行结果:
    1    学生1    初中1
    2    学生1    高中1
    3    学生1    大学1
    4    学生3    高中1
    5    学生3    大学2
      

  5.   

    select * from xxx 
    where student in (
    select student from xxx
    having count(*)  > 1
    group by student
    intersect
    select student from xxx
    where school = '高中1')
      

  6.   


    --稍有点复杂,有空再想想怎么简化
    select c.* from 
    stu_info_tab c, 
    (
    select student
    from stu_info_tab a 
    where exists (select 1 from stu_info_tab b where a.student = b.student and school='高中1') 
    group by student  having count(school) > 1
    )d
    where c.student = d.student;
      

  7.   


    --这个好理解一点
    select c.* from
    (
    --cond2
    select * from stu_info_tab a 
    where exists (select 1 from stu_info_tab b where a.student = b.student and school='高中1') 
    )c, 
    (
    --cond1
    select student
    from stu_info_tab a 
    group by student  having count(school) > 1
    )d 
    where c.student = d.student;
      

  8.   

    select * from t where student in (
      select student from t group by student having count(1) > 1 
      intersect 
      select student from t where school = '高中1' )