Question: Here's my table A

```
orderID groupID   nameID
1       grade A   foo
2       grade A   bar
3       grade A   rain
1       grade B   rain
2       grade B   foo
3       grade B   bar
1       grade C   rain
2       grade C   bar
3       grade C   foo

```

Desired result:

```
rain
bar
foo

```

I need `nameID` of `max(orderID)` from each grade. I can get right `orderID` from each grade, but `nameID` always stays as the first.

Thanks a Lot!

---

Praveen gave the right query! Extra question under his answer

Answer: 
Here is an appropriate query, using a correlated subquery:

```
select orderID, groupID, nameID
from A
where orderId = (select max(OrderId) from A a2 where A.groupId = a2.groupId);

```

If you want to do this with aggregation, you can use the `group_concat()`/`substring_index()` trick:

```
SELECT max(orderID) as orderID, groupId,
       substring_index(group_concat(nameId order by orderId desc), ',', 1) as nameID
FROM A
GROUP BY groupID;

```
```
SELECT * FROM (select
  max(`orderID`) as maxID, `groupID`, `nameID`
from
  Table1
GROUP BY `groupID`, `nameID`
ORDER BY maxID desc) abc
GROUP BY GROUPID

```

**[Fiddle With my test data](http://www.sqlfiddle.com/#!2/e94e8f/5)**

**[Fiddle with your data](http://www.sqlfiddle.com/#!2/afdc6/1)**