Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Max from each Subset

I'm banging my head here. I feel pretty stupid because I'm sure I've done something like this before, but can't for the life of me remember how. One of those days I guess >.<

Say I have the following data: ---> and a query which returns this: ---> But I want this:

ID   FirstID              ID   FirstID                ID   FirstID
--   -------              --   -------                --   -------
1     1                   1    1                      7    1
2     1                   3    3                      3    3
3     3                   4    4                      6    4
4     4                   5    5                      5    5
5     5
6     4
7     1

Notice that my query returns the records where ID = FirstID, but I want it to return the Max(ID) for each subset of unique FirstID. Sounds simple enough right? That's what I thought, but I keep getting back just record #7. Here's my query (the one that returns the second block of figures above) with some test code to make your life easier. I need this to give me the results in the far right block. It should be noted that this is a self-joining table where FirstID is a foreign key to ID. Thanks :)

declare @MyTable table (ID int, FirstID int)
insert into @MyTable values (1,1),(2,1),(3,3),(4,4),(5,5),(6,4),(7,1)
select ID, FirstID
from @MyTable
where ID = FirstID
like image 544
Chiramisu Avatar asked Nov 15 '11 01:11

Chiramisu


People also ask

How do I SELECT 3 max values in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.

Can Max function be used in GROUP BY?

The following selects the maximum salary from the Employee table. The following query gets all employees whose salary is maximum. The MAX() is an aggregate function, so it can be used in Group By queries.

Can we use max with * in SQL?

Try using this SQL SELECT statement: SELECT * FROM employees WHERE department_id=30 AND salary = (SELECT MAX(salary) FROM employees WHERE department_id=30); This will return the employee information for only the employee in department 30 that has the highest salary.

How do you SELECT Max in SQL?

The SQL MIN() and MAX() Functions The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.


1 Answers

Does this work

declare @MyTable table (ID int, FirstID int)
insert into @MyTable values (1,1),(2,1),(3,3),(4,4),(5,5),(6,4),(7,1)

Select FirstID, Max (Id) ID
From @MyTable
Group BY FirstID

Results in

FirstID     ID
----------- -----------
1           7
3           3
4           6
5           5
like image 155
Raj More Avatar answered Sep 29 '22 05:09

Raj More