日期:2014-05-17 浏览次数:20548 次
create table teacher (id int, name varchar(10), sex varchar(4)) insert into teacher select 1, '王老师', '男' union all select 2, '李老师', '男' union all select 3, '余老师', '女' union all select 4, '张老师', '女' create table student (id int, name varchar(10), teacherId int) insert into student select 1, '张三', 1 union all select 2, '李四', 1 union all select 3, '王五', 2 union all select 4, '宋六', 1 union all select 5, '郑七', 3 CREATE TABLE graduatedStudent(id INT, TIME DATE ,isGraduated VARCHAR(10)) INSERT INTO graduatedStudent SELECT 1, '2010', 'true' UNION ALL SELECT 3, '2000' ,'true' UNION ALL SELECT 4, '2003' ,'true' select a.* from teacher a inner join (select teacherid,count(1) [数量] from student a INNER JOIN graduatedStudent b ON a.id=b.id WHERE isGraduated='true' group by teacherid) b on a.id=b.teacherId order by b.[数量] /* id name sex ----------- ---------- ---- 2 李老师 男 1 王老师 男 (2 行受影响) */
------解决方案--------------------
create table teacher (id int, name varchar(10), sex varchar(4)) insert into teacher select 1, '王老师', '男' union all select 2, '李老师', '男' union all select 3, '余老师', '女' union all select 4, '张老师', '女' create table student (id int, name varchar(10), teacherId int) insert into student select 1, '张三', 1 union all select 2, '李四', 1 union all select 3, '王五', 2 union all select 4, '宋六', 1 union all select 5, '郑七', 3 CREATE TABLE graduatedStudent(id INT, TIME DATETIME ,isGraduated VARCHAR(10)) INSERT INTO graduatedStudent SELECT 1, '2010', 'true' UNION ALL SELECT 3, '2000' ,'true' UNION ALL SELECT 4, '2003' ,'true' select t.*,isnull(rn,0) as rn from teacher t left join ( SELECT teacherId,count(teacherId) as rn from student s left join graduatedStudent g on s.id=g.id and isGraduated='true' group by teacherId ) r on t.id=r.teacherId order by isnull(rn,0) /*id name sex rn ----------- ---------- ---- ----------- 4 张老师 女 0 2 李老师 男 1 3 余老师 女 1 1 王老师 男 3