简体   繁体   English

SQL 获取每个对象的最频繁项

[英]SQL get the most frequent item for each object

Table: Food
+------+------+
|Person| Food |
+------+------+
|  A   | Apple|
|  A   | Bread|
|  A   | Bread|
|  A   | Bread|
|  B   |Orange|
|  B   |Orange|
|  B   |Orange|
|  C   |Orange|
|  C   |Orange|
+------+------+

How do you find the the most frequent food a person ate and how many times he ate it.你如何找到一个人吃的最频繁的食物以及他吃了多少次。 The output would be something like输出将类似于

A - Bread - 3
B - Orange - 3
C - Orange - 2

I have tried this.我试过这个。 But right now the count just gives the amount of food he ate and not the most frequent one.但是现在计数只是给出了他吃的食物量,而不是最常吃的食物。

SELECT PERSON,FOOD, COUNT(FOOD)
FROM FOOD
GROUP BY FOOD
ORDER BY COUNT(FOOD)

Here is a working solution:这是一个有效的解决方案:

SELECT PERSON, FOOD, MAX(c) FROM  
(SELECT PERSON, FOOD, COUNT(*) AS c  
FROM FOOD  
GROUP BY PERSON, FOOD  
ORDER BY c DESC) AS v  
GROUP BY PERSON;

Here is a link to a SqlFiddle: http://sqlfiddle.com/#!9/726798/45这是 SqlFiddle 的链接: http ://sqlfiddle.com/#!9/726798/45

If you want to show the whole list of food counts per person, you can do this:如果你想显示每人食物数量的完整列表,你可以这样做:

SELECT PERSON, FOOD, COUNT(*) AS C
FROM FOOD
GROUP BY PERSON, FOOD
ORDER BY PERSON, C DESC

SqlFiddle: http://sqlfiddle.com/#!9/726798/53 SqlFiddle: http ://sqlfiddle.com/#!9/726798/53

See here Get top n records for each group of grouped results for some more information about finding the arbitrary top n most frequent.请参阅此处获取每组分组结果的前 n 条记录,以获取有关查找任意前n最频繁的更多信息。

You can add rank to your query and make it a subquery to select on that:您可以为查询添加排名,并使其成为子查询以供选择:

SELECT PERSON, FOOD, food_count
FROM (
    SELECT PERSON,FOOD,COUNT(FOOD) food_count, DENSE_RANK(COUNT(FOOD)) OVER (PARTITION BY PERSON) food_rank
    FROM FOOD
    GROUP BY PERSON, FOOD
) ranked_counted_foods
WHERE food_rank = 1

To select the top three food counts for a person, change to = 3 .要选择一个人的前三个食物数量,请更改为= 3 Then RANK() and DENSE_RANK() will give slightly different behaviors when there are ties.然后 RANK() 和 DENSE_RANK() 在有平局时会给出稍微不同的行为。 DENSE_RANK will return 2 even if it returned multiple 1s for ties; DENSE_RANK 将返回 2,即使它返回多个 1 表示平局; RANK will skip numbers when there are ties.当有平局时,RANK 将跳过数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM