【问题标题】:Finding the entry with the most occurrences per group查找每组出现次数最多的条目
【发布时间】:2021-02-01 08:22:25
【问题描述】:

我有以下(简化的)架构。

CREATE TABLE TEST_Appointment(
    Appointment_id INT AUTO_INCREMENT PRIMARY KEY,
    Property_No INT NOT NULL,
    Property_Type varchar(10) NOT NULL
);

INSERT INTO TEST_Appointment(Property_No, Property_Type) VALUES
    (1, 'House'),
    (1, 'House'),
    (1, 'House'),
    (2, 'Flat'),
    (2, 'Flat'),
    (3, 'Flat'),
    (4, 'House'),
    (5, 'House'),
    (6, 'Studio');

我正在尝试编写一个查询来获取每个属性类型组中约会最多的属性。一个示例输出是:

Property_No | Property_Type | Number of Appointments
-----------------------------------------------------
1           | House         | 3
2           | Flat          | 2
6           | Studio        | 1

我有以下查询来获取每个属性的约会数量,但我不知道如何从那里开始

SELECT Property_No, Property_Type, COUNT(*)
from TEST_Appointment
GROUP BY Property_Type, Property_No;

【问题讨论】:

    标签: mysql sql count aggregate-functions greatest-n-per-group


    【解决方案1】:

    如果您运行的是 MySQL 8.0,则可以使用聚合和窗口函数:

    select *
    from (
        select property_no, property_type, count(*) no_appointments,
            rank() over(partition by property_type order by count(*) desc) rn
        from test_appointment
        group by property_no, property_type
    ) t
    where rn = 1
    

    在早期版本中,一个选项使用having 子句和行限制相关子查询:

    select property_no, property_type, count(*) no_appointments
    from test_appointment t
    group by property_no, property_type
    having count(*) = (
        select count(*)
        from test_appointment t1
        where t1.property_type = t.property_type
        group by t1.property_no
        order by count(*) desc
        limit 1
    )
    

    请注意,这两个查询都允许平局,如果有的话。

    【讨论】:

    • 谢谢@GMB,我认为第二种方法最适合我,尤其是它看起来更通用。
    • @MMansour:第一种方法效率更高,因为表只扫描一次。仅当您未运行 MySQL 8.0 时才使用第二个选项。
    猜你喜欢
    • 2019-10-27
    • 2011-04-29
    • 1970-01-01
    • 2011-04-17
    • 2013-01-17
    • 2017-06-27
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多