1

我有表格作为与以下值的链接

++++++++++++++++++++++++++
+ 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      +
++++++++++++++++++++++++++
4

2 回答 2

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

要获得更快的性能,请添加INDEXon 列industry

于 2013-02-23T17:44:41.210 回答
0

你也可以试试这个。它将每个行业作为一个群体来计算。然后按该数字分组。(SQLFIDDLE 是非常方便的工具)

演示

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;
于 2013-02-23T18:29:06.463 回答