每个类别被提及的次数
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 列上没有唯一约束(尽管您可以添加一个,然后可以a.category
从 ORDER BY 子句中删除该术语)。