SQL组 - 最常见的

时间:2017-10-26 21:22:15

标签: mysql sql

假设我有下表

+-----------------------+----------------+
| PERSON                | ATE            |
+-----------------------+----------------+
| Joe                   | Chicken        |
| Joe                   | Chicken        |
| Joe                   | Chicken        |
| Joe                   | Tuna           |
| Joe                   | Tuna           |
| Joe                   | Chicken        |
| Joe                   | Tuna           |
| Joe                   | Chicken        |
| Joe                   | Tuna           |
| Joe                   | Tuna           |
| Joe                   | Tuna           |
| Joe                   | Chicken        |
| Joe                   | Tuna           |
| Joe                   | Tuna           |
| Joe                   | Chicken        |
| Joe                   | Tuna           |
| Joe                   | Tuna           |
| Joe                   | Tuna           |
| Rob                   | Chicken        |
| Rob                   | Tuna           |
| Rob                   | Chicken        |
| Rob                   | Chicken        |
| Rob                   | Chicken        |
| Rob                   | Chicken        |
| Jonathan              | Tuna           |
| Jonathan              | Tuna           |
| Jonathan              | Chicken        |
| Jonathan              | Tuna           |
| Jonathan              | Chicken        |
+-----------------------+----------------+

我想为每个人找到最常吃的食物。因此,期望的结果将是:

+-----------------------+----------------+
| PERSON                | ATE            |
+-----------------------+----------------+
| Joe                   | Tuna           |
| Rob                   | Chicken        |
| Jonathan              | Tuna           |
+-----------------------+----------------+

当然,我会GROUP BY(人)。之后,我必须找到每组中最常食用的物品。如果它们是数字就很容易,因为我可以使用MAX函数,但我不知道如何在一堆中挑选出最受欢迎的字符串。

你将如何完成我在SQL中尝试做的事情?

2 个答案:

答案 0 :(得分:3)

您可以使用相关子查询:

select distinct t1.PERSON, (
    select ATE
    from myTable t2
    where t2.PERSON = t1.PERSON
    group by ATE
    order by count(*) desc
    limit 1
) as ATE
from myTable t1

如果您有联系,此查询将“随机”选择一个吃得最多的项目。

使用MySQL 8或MariaDB 10.2(两者都不稳定),您将能够使用CTE(公用表表达式

with t1 as (
    select PERSON, ATE, count(*) as cnt
    from myTable
    group by PERSON, ATE
), t2 as (
    select PERSON, max(cnt) as cnt
    from t1
    group by PERSON
)
    select *
    from t1
    natural join t2

在关系上,此查询可能会为每个组返回多行(PERSON)。

答案 1 :(得分:1)

通常情况下,您需要多次汇总数据以获取每人和食物的数量,然后按人数计算,然后重新计算以便进行比较......

但有一个诀窍:用食物粘上计数:

Joe Chicken      00000000000007Chicken
Joe Tuna         00000000000011Tuna
Jonathan Chicken 00000000000002Chicken 
Jonathan Tuna    00000000000003Tuna 
Rob Chicken      00000000000005Chicken 
Rob Tuna         00000000000001Tuna 

然后获取每个人的最大条目(例如00000000000011Tuna的{​​{1}})并删除该号码:

Joe

http://rextester.com/GVO98572