0

I have a following table.

id    name     data
1     DAN      xxxxxxxxx
2     ANTONY   xxxxxxxxx
3     DAN      xxxxxxxxx
4     DAN      xxxxxxxxx
5     JOSEPH   xxxxxxxxx
6     ANTONY   xxxxxxxxx
7     JOSEPH   xxxxxxxxx

I want to first sort the table using ID and then group by name. eg.

7    JOSEPH  xxxxxxxxx
5    JOSEPH  xxxxxxxxx
6    ANTONY  xxxxxxxxx
2    ANTONY  xxxxxxxxx
4    DAN     xxxxxxxxx
3    DAN     xxxxxxxxx
1    DAN     xxxxxxxxx

I tried various combinations of ORDER BY and also tried ORDER BY FIELD but unable to get the desired result

3
  • 1
    have you tried select * from table order by id,name ? Commented Mar 14, 2018 at 9:38
  • Yes I tried that, but didn't get the expected results Commented Mar 14, 2018 at 9:39
  • ORDER BY correlated subquery? Commented Mar 14, 2018 at 9:41

3 Answers 3

2

Try using

select *, (select max(id) from tab t2 where t2.name = t1.name) m
from tab t1
order by m desc, id desc;

dbfiddle demo

Sign up to request clarification or add additional context in comments.

Comments

0

You could also use window function to get the maximum id for each name and use them for ordering purpose.

SELECT *,
        MAX(id) OVER(PARTITION BY name ORDER BY id DESC) Ord
FROM table t
ORDER BY Ord DESC

Comments

0

You can use a subquery in the order by, so you can express this as:

select t.*
from t
order by (select max(id) from t t2 where t2.name = t.name) desc, id desc;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.