我将表格作为与以下值的链接
++++++++++++++++++++++++++
+ company_id + industry +
++++++++++++++++++++++++++
+ 1 + a +
+ 2 + b +
+ 3 + a +
+ 4 + c +
+ 5 + a +
+ 6 + c +
+ 7 + a +
++++++++++++++++++++++++++
a有计数4,c有计数2,b有计数1
我希望返回
的查询++++++++++++++++++++++++++
+ company_id + industry +
++++++++++++++++++++++++++
+ 1 + a +
+ 3 + a +
+ 5 + a +
+ 7 + a +
+ 4 + c +
+ 6 + c +
+ 2 + b +
++++++++++++++++++++++++++
答案 0 :(得分:4)
下面的查询使用子查询,该子查询分别计算每个industry
的记录数。然后它的结果再次返回到原始表上,并按子查询的总计数对记录进行排序。
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT industry, COUNT(*) totalCount
FROM tableName
GROUP BY industry
) b ON a.industry = b.industry
ORDER BY b.totalCount DESC, a.company_ID ASC
要获得更快的效果,请在列INDEX
上添加industry
。
答案 1 :(得分:0)
你也可以试试这个。它正在计算每个行业作为一个群体的出现。然后按该号码分组。 (SQLFIDDLE是非常方便的工具)
Demo:
select a.company_id, a.industry,
(select count(*) as cnt from tbl b
where a.industry = b.industry) as order_by
from tbl a
order by order_by desc;