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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With