我想你一定有如果班級中有多個具有相同分數的人,則「分組依據」和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) –