日期:2014-05-18  浏览次数:20461 次

关于group by
SQL code

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

CREATE TABLE [dbo].[TB_Student] (
    [strStudent] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
    [strClass] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
    [nScore] [int] NOT NULL 
) ON [PRIMARY]
GO

insert into TB_Student(strStudent,strClass,nScore) values('张三','语文',65)
insert into TB_Student(strStudent,strClass,nScore) values('张三','数学',85)
insert into TB_Student(strStudent,strClass,nScore) values('张三','英语',90)
insert into TB_Student(strStudent,strClass,nScore) values('李四','语文',56)
insert into TB_Student(strStudent,strClass,nScore) values('李四','数学',67)
insert into TB_Student(strStudent,strClass,nScore) values('李四','英语',89)
insert into TB_Student(strStudent,strClass,nScore) values('王五','语文',56)
insert into TB_Student(strStudent,strClass,nScore) values('王五','数学',55)
insert into TB_Student(strStudent,strClass,nScore) values('王五','英语',87)

/*
结果 

姓名   学科   成绩
'张三','英语',90
'李四','英语',89
'王五','英语',87
*/

--谢谢 各位





------解决方案--------------------
SQL code
select * from TB_Student t
where not exists(select 1 from TB_Student where strStudent=t.strStudent and nScore>t.nScore)

------解决方案--------------------
 
为什么不直接用

select * from dbo.TB_Student where strclass='英语'
------解决方案--------------------
貌似和group by 没有关系

SQL code
select * from [TB_Student] where strClass='英语'

------解决方案--------------------
SQL code

select * from TB_Student a
where nScore=(select max(nScore) from TB_Student where strStudent=a.strStudent)