SQL:按多个字段分组

时间:2014-06-17 20:10:11

标签: mysql sql group-by multiple-columns

我需要选择一些值,将它们分组并按多个字段排序。 这是我的小提琴:http://sqlfiddle.com/#!2/a80eb/3

我需要实现的是,从表packet_data中选择一行,以获取给定的client_mac值和drone_id列中的每个不同项。对于client_mac和{的给定组合,此行应包含drone_idantenna_signal的值和drone_id列的最常见值{1}}。

client_mac是表drone_id中的外键,此表中有一列drones。我只需要关注map_id表中packet_data表中具有特定map_id的那些行。

我想要的结果应该是:

drones

我当前的SQL查询是:

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

我目前的结果:

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

1 个答案:

答案 0 :(得分:2)

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

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
);

如果需要,加入其他表格并不困难。但是,如果有两个对同一个client_mac和drone_id具有相同计数的antenna_signals,则会显示两行。在更新的小提琴http://sqlfiddle.com/#!2/a80eb/80

中查看