【问题标题】:Find most occurrences of values then sort by number of occurrences [duplicate]查找出现次数最多的值,然后按出现次数排序[重复]
【发布时间】:2021-10-28 04:20:48
【问题描述】:

我有一个名为“places”的表,它在一列中具有类似的值,如下面的数据所示,我想找到不同的值,显示它们的计数/出现次数,按降序对它们进行排序,并限制结果只有三个值:

name           residents
San Andres     50
San Felipe     143
San Juan       810
San Pablo      352
San Pedro      229
San Vicente    62
Santa Maria    500
San Juan       129
San Andres     88
Santo Rosario  55
San Juan       717
San Vicente    111

我希望结果是:

San Juan       3
San Andres     2
San Vicente    2

我尝试了以下语句,但它给出了不同的结果:

SELECT DISTINCT(name) AS distinctName, COUNT(name) FROM place ORDER BY COUNT(distinctName) DESC LIMIT 3;

【问题讨论】:

  • 只需使用GROUP BY

标签: sql sqlite distinct


【解决方案1】:

要在不同的行上累积结果,您需要使用GROUP BYGROUP BY 为每个 GROUP BY 字段的唯一组合返回一个结果行。

本教程提供了一些关于GROUP BY 工作原理的示例 https://www.w3schools.com/sql/sql_groupby.asp

您可能还想查看之前的相关问题How does GROUP BY work?

【讨论】:

    【解决方案2】:
    select name, count(*) from place group by (name) order by count(*) desc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-29
      • 2019-10-27
      • 2011-05-16
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      相关资源
      最近更新 更多