Question : How do I select the first row from each subset of data within a query result?

Hi!

I've got a MS SQL 2000 query that produces the following result:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
Schedule    Date         Class          Period               Count       
----------- ------------ -------------- -------------------- ----------- 
441         2008/07/28   DEVL 101       A3201                205 
441         2008/07/28   DEVL 101       ZR019                102
 ...
441         2008/07/28   DEVL 101       BF012                1
554         2009/02/14   DEVL 154       X5002                384 
554         2009/02/14   DEVL 154       W8098                98
 ...
554         2009/02/14   DEVL 154       H2309                5


From this query, I want to select the Schedule, Date, Class, and Period with the highest Count from the rows that contain the same values for Schedule, Date, and Class.

The result should look like this:

1:
2:
3:
4:
5:
6:
Schedule    Date         Class          Period               Count       
----------- ------------ -------------- -------------------- ----------- 
441         2008/07/28   DEVL 101       A3201                205 
554         2009/02/14   DEVL 154       X5002                384
 ...


Answer : How do I select the first row from each subset of data within a query result?

SELECT t1.Schedule, t1.Date, t1.Class, t1.Period, t1.[Count]
FROM SomeTable t1 INNER JOIN
   (SELECT t2.Schedule, t2.Date, t2.Class, MAX(t2.[Count]) AS MaxCount
   FROM SomeTable
   GROUP BY t2.Schedule, t2.Date, t2.Class) x ON t1.Schedule = x.Schedule AND t1.Date = x.Date AND t1.Class = x.Class AND t1.[Count] = x.MaxCount
Random Solutions  
 
programming4us programming4us