按一个元素的出现次数对表进行排序

时间:2013-01-26 02:20:02

标签: mysql

id Category Name
1  Sports   name1
2  Food     name2
3  Sports   name3
4  Social   name4
5  TV       name5
6  Food     name6
7  Sports   name7
8  TV       name8

我如何查询*按提及最多的类别排序?结果应该是这样的:

Sports name1
Sports name3
Sports name7
Food name2
Food name6

and so.

1 个答案:

答案 0 :(得分:0)

提及每个类别的次数

SELECT category, COUNT(*) AS cat_count
  FROM anonymous_table
 GROUP BY category

按要求排序的数据

SELECT a.category, a.name
  FROM anonymous_table AS a
  JOIN (SELECT category, COUNT(*) AS cat_count
          FROM anonymous_table
         GROUP BY category
       ) AS c ON a.category = c.category
 ORDER BY c.cat_count DESC, a.name 

  

出于某种原因,它没有完成这项工作。

我在Informix中尝试了上面的SQL,并且它“有效”,但给出了一个意想不到但可解释的答案:

Sports    name1
Sports    name3
Sports    name7
Food      name2
TV        name5
Food      name6
TV        name8
Social    name4

没有任何东西可以将Food行组合在一起,并且名称上的排序确实迫使它们被分开。因此,ORDER BY子句需要有一个额外的条件:

SELECT a.category, a.name
  FROM anonymous_table AS a
  JOIN (SELECT category, COUNT(*) AS cat_count
          FROM anonymous_table
         GROUP BY category
       ) AS c ON a.category = c.category
 ORDER BY c.cat_count DESC, a.category, a.name;

这给出了一个合理的结果:

Sports    name1     
Sports    name3     
Sports    name7     
Food      name2     
Food      name6     
TV        name5     
TV        name8     
Social    name4     

如果你想要食物之前的电视,你必须为此提出一些订购方案。在该示例中,您可以按类别降序排序。在具有不同类别的准任意排序的一般情况下,您将添加一个类别表和一些排序列(可能是一个ID,更可能与ID列分开),当其他标准为时,它们确定不同类别的相对排序。相同的:

CREATE TABLE Category(Name CHAR(10) NOT NULL PRIMARY KEY, Ordering INTEGER NOT NULL);
INSERT INTO Category(Name, Ordering) VALUES('Sports', 10);
INSERT INTO Category(Name, Ordering) VALUES('TV',     20);
INSERT INTO Category(Name, Ordering) VALUES('Food',   30);
INSERT INTO Category(Name, Ordering) VALUES('Social', 40);

SELECT a.category, a.name
  FROM anonymous_table AS a
  JOIN category        AS b ON a.category = b.name
  JOIN (SELECT category, COUNT(*) AS cat_count
          FROM anonymous_table
         GROUP BY category
       ) AS c ON a.category = c.category
 ORDER BY c.cat_count DESC, b.ordering, a.category, a.name;

您仍然需要按类别排序以确保正确分组,因为Category.Name列上没有唯一约束(尽管您可以添加一个,然后您可以从ORDER中删除a.category个术语BY子句)。