这个sql语句:列出各门课程成绩最好的两位学生?

表:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[test]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[test]
GO

CREATE TABLE [dbo].[test] (
 [id] [int] IDENTITY (1, 1) NOT NULL ,
 [subject] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
 [score] [int] NULL
) ON [PRIMARY]

--说明:id,学生ID,subject 课程,score分数
GO


insert into test

select '1',89 union all
select '1',80 union all
select '2',100 union all
select '2',77 union all
select '2',78 union all
select '3',92 union all
select '4',69 union all
select '4',78 union all
select '1',86 union all
select '2',81 union all
select '3',90 union all
select '3',66 union all
select '2',79



答案已经有了:
select distinct t1.*
from test t1
where t1.id in
(select top 2 test.id from test where subject = t1.subject order by score desc)
order by t1.subject

但是,我不太明白 select top 2 test.id from test where subject = t1.subject order by score desc  到底是怎么意思?逻辑上结合where .. in .. 怎样实现的? 本人比较笨,请老大们详细指点,谢了!

posted @ 2005-07-19 13:23  Ready!  阅读(1701)  评论(1编辑  收藏  举报