我想你一定有如果班级中有多个具有相同分数的人,则“分组依据”和MAX()存在问题。
我解决了它,如果你还不知道这是什么,你可以看看here。它比开始时看起来更容易!
我知道这可能是一种可怕的方式来做到这一点,但它很容易理解,它的工作原理! :d
USE [TestDB]
GO
DECLARE @class char(10), @testscore int;
DECLARE @result Table
(
Name char(10),
Class char(10),
TestScore int
);
-- Get Classes and their Maxima
DECLARE TestScore_cursor CURSOR FOR SELECT [class], MAX([testscore]) FROM [student] GROUP BY [class];
OPEN TestScore_cursor;
-- Perform the first fetch.
FETCH NEXT FROM TestScore_cursor INTO @class, @testscore;
-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
-- Search Students by Class and Score and add them to tempTable @result
INSERT INTO @result SELECT [name], [class], [testscore] From [student] where [testScore] = @testscore AND [class] = @class;
FETCH NEXT FROM TestScore_cursor INTO @class, @testscore;
END
-- Show the Result
SELECT * FROM @result;
CLOSE TestScore_cursor;
DEALLOCATE TestScore_cursor;
GO
见:http://dba.stackexchange.com/questions/1002/how-to-get-the-max-row –
[从每个组中抓取具有最高值的行的可能的复制?](http://stackoverflow.com/questions/9180283/grabbing-the-row-with-the-highest-value-from-each-group) –