日期:2014-05-17 浏览次数:20438 次
CREATE TABLE [dbo].[studentInfo](
[id] [int] IDENTITY(1,1) NOT NULL,
[subject] [varchar](50) NOT NULL,
[studentID] [int] NOT NULL,
[isPass] [int] NOT NULL,
[teacherID] [int] NOT NULL)
CREATE TABLE [dbo].[teacherInfo](
[id] [int] IDENTITY(1,1) NOT NULL,
[teacherID] [int] NOT NULL,
[Age] [int] NOT NULL,
[sex] [int] NOT NULL)
insert into teacherInfo(teacherid,age,sex) values(3,50,0)
insert into teacherInfo(teacherid,age,sex) values(15,35,0)
insert into studentInfo(subject,studentid,ispass,teacherid) values('语文',1,0,3)
insert into studentInfo(subject,studentid,ispass,teacherid) values('数学',1,0,3)
insert into studentInfo(subject,studentid,ispass,teacherid) values('英语',1,0,3)
insert into studentInfo(subject,studentid,ispass,teacherid) values('语文',2,1,15)
insert into studentInfo(subject,studentid,ispass,teacherid) values('数学',2,1,15)
insert into studentInfo(subject,studentid,ispass,teacherid) values('英语',2,1,15)
with ranking(teachid,ranknum)
as
(
select s.teacherid,row_number() over(order by count(*) desc,sum(t.age) desc) from studentinfo s left join teacherinfo t on s.teacherid=t.teacherid where s.ispass=1 group by s.teacherid
)
select * from ranking
;WITH ranking ( teachid, ranknum )
AS
(
SELECT
s.teacherid ,
ROW_NUMBER() OVER ( ORDER BY SUM(ispass) DESC, MAX(t.age) DESC ) --isPass相加(这是关键点),年龄取原始年龄更形象(虽然效果一样)