GPiter
GPiter

Reputation: 799

Order by multiple columns not working as expected

I have this sql :

GROUP BY dc.year, dc.month, d.user_id
ORDER BY dc.year DESC, d.user_id ASC

The result is :

UserId         Month            Year
 1               1              2020
 1               4              2020
 1               2              2020
 2               5              2019
 2               1              2019

Expected result :

UserId         Month            Year
 1               1              2020
 1               2              2020
 1               4              2020
 2               1              2019
 2               5              2019  

But I want to order and by month not only by year. I tried like this ORDER BY dc.year DESC, dc.month ASC, d. user_id ASC, but not working as expected because I want to liste each user order by year desc and by month asc. Can you help me please ?

Upvotes: 1

Views: 68

Answers (4)

Tushant Rajpal
Tushant Rajpal

Reputation: 21

You can use the below code to get the result as per your expected result. I have tried it from my end and getting the expected result.

GROUP BY dc.year, dc.month, d.user_id
order by dc.year DESC, dc.month asc, d.user_id asc

Check below the image with solution:

https://snipboard.io/NeAHB5.jpg

Upvotes: 0

Akshata L
Akshata L

Reputation: 1

ORDER BY dc.user_id ASC, dc.month ASC, dc.year DESC;

Upvotes: 0

django-unchained
django-unchained

Reputation: 844

Looks like you don't need user_id in the ORDER BY clause.

Try this:

ORDER BY dc.year DESC, d.user_id, dc.month 

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269743

I want to liste each user order by year desc and by month asc.

That describes:

ORDER BY d.user_id, dc.year DESC, dc.month

Upvotes: 2

Related Questions