我需要选择一些值,将它们分组并按多个字段排序。
这是我的小提琴:http://sqlfiddle.com/#!2/a80eb/3
我需要实现的是,从表packet_data中为给定值client_mac和列drone_id中的每个不同项选择一行。对于给定的client_macdrone_id组合,此行应包含antenna_signaldrone_id的值和client_mac列的最常用值。
drone_id是表drones的外键,此表中有一列map_id。我只需要关注packet_data表中那些在map_id表中有特定drones的行。
我想要的结果应该是:

CLIENT_MAC          DRONE_ID    ANTENNA_SIGNAL
3c:77:e6:17:9d:1b   1           -37
3c:77:e6:17:9d:1b   2           -57

我当前的SQL查询是:
SELECT `packet_data`.`client_mac`,
       `packet_data`.`drone_id`,
       `packet_data`.`antenna_signal`,
       count(*) AS `count`
FROM `packet_data`
JOIN `drones` ON `packet_data`.`drone_id`=`drones`.`custom_id`
WHERE `drones`.`map_id` = 11
  AND `client_mac`="3c:77:e6:17:9d:1b"
GROUP BY drone_id,
         `packet_data`.`antenna_signal`
ORDER BY `packet_data`.`drone_id`,
         count(*) DESC

我现在的结果是:
CLIENT_MAC          DRONE_ID    ANTENNA_SIGNAL
3c:77:e6:17:9d:1b   1           -37
3c:77:e6:17:9d:1b   1           -36
3c:77:e6:17:9d:1b   2           -57
3c:77:e6:17:9d:1b   2           -56

最佳答案

您可以使用一个不太好的关联子查询(也可以在子查询上)获得所需的结果。我不知道它将如何通过大量数据进行扩展:

SELECT
    -- the desired columns
    client_mac,
    drone_id,
    antenna_signal,
    amount               -- I added this so I could easily check the result
FROM (
    -- give me the count of every value of the antenna_signal column
    -- for each combination of client_mac, drone_id and antenna_signal
    SELECT
        client_mac,
        antenna_signal,
        drone_id,
        COUNT(antenna_signal) AS amount
    FROM
        packet_data
    WHERE
        client_mac = '3c:77:e6:17:9d:1b'
    GROUP BY
        client_mac,
        drone_id,
        antenna_signal
) as1
WHERE
    -- but I want only those rows with the highest count of equal antenna_signal
    -- values per client_mac and drone_id
    amount = (
        SELECT
            MAX(as2.amount)
        FROM (
            SELECT
                pd2.client_mac,
                pd2.antenna_signal,
                pd2.drone_id,
                COUNT(pd2.antenna_signal) AS amount
            FROM
                packet_data pd2
            WHERE
                client_mac = '3c:77:e6:17:9d:1b'
            GROUP BY
                client_mac,
                drone_id,
                antenna_signal
            ) as2
        WHERE
            as1.client_mac = as2.client_mac AND as1.drone_id = as2.drone_id
);

如果需要的话,连接其他表应该不会太困难。但如果同一个客户端mac和无人机id有两个计数相等的天线信号,则显示两行。

10-08 19:45