XXXmax
XXXmax

Reputation: 33

Use order by without changing the order of the groups

I am trying to find the count of sub categories with respect to their main categories. I want to further order them by desc by each main category. Currently my code

select ShipperID, EmployeeID, count(*)
from orders
group by 1, 2
order by 3 desc

This changes the groups totally. I would be very obliged if I can get help how to order it internally by each group.

Upvotes: 1

Views: 72

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269693

I suspect that you simply want ShipperId as the first key in the order by:

select ShipperID, EmployeeID, count(*)
from orders
group by ShipperID, EmployeeID
order by ShipperID, count(*) desc;

Upvotes: 2

Diego Rafael Souza
Diego Rafael Souza

Reputation: 5313

You just need to decalre the fields on order by clause in the same sequence you're expecting, like this:

select ShipperID, EmployeeID, sum(amount) 
from ORDERS 
group by 1, 2 
order by 1, 2, 3 desc

You can take a look into this working example hosted at db-fiddle.com

I hope it helps.

Upvotes: 1

Related Questions