Reputation: 5288
Is it possible to order return rows with a criteria on a sum group ?
For example, my data are :
Id Price Product Category
1 12 Book1 Car
2 1 Book2 Art
3 8 Book3 Car
4 7 Book4 Art
5 11 Book5 Car
6 24 Book6 Bridge
As the sum of Car books is 31, the sum of Art books is 8 and the sum of Bridge books is 24, I would like to have the following result (Car first, then Bridge and then Art):
Id Price Product Category
1 12 Book1 Car
3 8 Book3 Car
5 11 Book5 Car
6 24 Book6 Bridge
2 1 Book2 Art
4 7 Book4 Art
On the other hand, I would like to add other Order by criteria (in the example, "Product" criteria). I have tried many things using ORDER BY and GROUP BY but it always aggregate my results.
Thanks for help !
Upvotes: 0
Views: 382
Reputation: 49095
You could do something like this:
select
l.* from table l
inner join (
select category, sum(price) as total from table group by category
) r
on l.category = r.category
order by r.total, <some_other_column>
This is the procedure I followed:
Upvotes: 6