Mysql 按组和条件排序

Mysql 按组和条件排序,mysql,sql,group-by,Mysql,Sql,Group By,是否可以使用sum组上的条件对返回行进行排序 例如,我的数据是: 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

是否可以使用sum组上的条件对返回行进行排序

例如,我的数据是:

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
由于汽车书籍的总数是31本,艺术书籍的总数是8本,桥梁书籍的总数是24本,我希望得到以下结果:首先是汽车,然后是桥梁,然后是艺术:

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
另一方面,我想在示例中添加其他orderby标准,即产品标准。 我尝试了很多使用ORDER BY和GROUP BY的方法,但它总是汇总我的结果


谢谢你的帮助

您可以这样做:

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>
这是我遵循的程序:

找到小计 将原始表连接到小计 按这些小计对原始表格进行排序
你可以这样做:

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>
这是我遵循的程序:

找到小计 将原始表连接到小计 按这些小计对原始表格进行排序
你为什么想要汽车->艺术->桥梁订单?你用什么来确定类别的顺序?你有车,然后是艺术,然后是桥,但那不是按你的总数排序的,因为艺术是介于车和桥之间的。我在订单上犯了一个错误。它是SumCar>SumBridge>sumart为什么要选择car->art->bridge顺序?您使用什么来确定类别的顺序?你有车,然后是艺术,然后是桥,但那不是按你的总数排序的,因为艺术是介于车和桥之间的。我在订单上犯了一个错误。这是SumCar>SumBridge>SumArt+1 OP需要r.total DESC的订单。。。但这只是细节。+1我认为查询内部联接时按类别分组可能也是必要的。+1 OP希望按r排序。total DESC。。。但这只是细节。+1我认为查询内部联接时按类别分组也是必要的。