I found a question that was very similar to this, but using features that seem to be exclusive to Oracle. I want to do this in SQL Server.
I have a table like this:
MyTable -------------------- MyTableID INT PK UserID INT Counter INT
Each user can have several lines with different values ββfor Counter in each line. I need to find the rows with the highest Counter value for each user.
How to do this in SQL Server 2005?
The best I can find is a query that returns MAX(Counter) for each UserID , but I need the whole row due to other data in this table that is not shown in my table definition for simplicity.
EDIT:. It occurred to me some of the answers in this post that I forgot about an important detail. It is possible to have 2+ lines where UserID can have the same MAX counter value. The example below is updated for expected data / output.
With this data:
MyTableID UserID Counter --------- ------- -------- 1 1 4 2 1 7 3 4 3 4 11 9 5 11 3 6 4 6 ... 9 11 9
I want these results to be repeated in MAX values, select the first event in any order that the SQL server selects. Which rows are returned is not important in this case, if the UserID / Counter pairs are different:
MyTableID UserID Counter --------- ------- -------- 2 1 7 4 11 9 6 4 6
sql sql-server sql-server-2005
Dan herbert
source share