SELECT a.name, a.ID
FROM Table1 AS a
INNER JOIN
(
SELECT name, COUNT(*) AS cnt
FROM Table1
GROUP BY name
) AS b
ON a.name = b.name
ORDER BY
b.cnt DESC,
a.ID;
WITH Counts (name, cnt) AS
(SELECT name, COUNT(*)
FROM Table1
GROUP BY name)
SELECT Table1.id, Table1.name
FROM Table1, Counts
INNER JOIN Counts
ON Table1.name = Counts.name
ORDER BY Counts.cnt DESC
3条答案
按热度按时间pokxtpni1#
一种方法是使用子查询的联接来查找每个名称的计数:
qpgpyjmq2#
按id分组时,会为每个元素创建一个单独的组,因为每个元素都有一个唯一的id。若要获取每个名称组的计数,需要按名称创建一个分组,然后将其与原始表联接,以便保留值。比如:
xoefb8l83#
哦,我明白了。您可以在
order by
:请注意
name
是第二个吗order by
钥匙。如果两个名称具有相同的计数,则这会将给定名称的所有行保持在一起。