如何在SQL中找到按ID分组的所有字段的最大平均值?

时间:2018-04-07 08:30:49

标签: sql mariadb

所以我有一个超过50个字段的庞大表格,我需要通过ID找到每个字段的最大平均值。我的表看起来像这样:

    +----+--------+--------+-----+---------+
    | ID | field1 | field2 | ... | field50 |
    +----+--------+--------+-----+---------+
    | 1  | 234    | 12     | ... | 634     |
    +----+--------+--------+-----+---------+
    | 2  | 1      | 69     | ... | 34      |
    +----+--------+--------+-----+---------+
    | 3  | 512    | 1000   | ... | 420     |
    +----+--------+--------+-----+---------+
    | 4  | 11     | 69     | ... | 34      |
    +----+--------+--------+-----+---------+
    | 3  | 522    | 1337   | ... | 78      |
    +----+--------+--------+-----+---------+
    | 2  | 18     | 698    | ... | 348     |
    +----+--------+--------+-----+---------+
    | 3  | 32     | 1910   | ... | 40      |
    +----+--------+--------+-----+---------+

我想知道是否有一种简单的方法可以做到这一点。现在,我正在尝试从包含每个ID的平均值的子查询中获取最大值。使用上面的示例表,子查询应该返回如下内容:

    +----+-------+-------+-----+-------+
    | ID | avg1  | avg2  | ... | avg50 |
    +----+-------+-------+-----+-------+
    | 1  | 234   | 12    | ... | 634   |
    +----+-------+-------+-----+-------+
    | 2  | 9.5   | ~990  | ... | 191   |
    +----+-------+-------+-----+-------+
    | 3  | ~355  | ~1416 | ... | 538   |
    +----+-------+-------+-----+-------+
    | 4  | 11    | 69    | ... | 34    |
    +----+-------+-------+-----+-------+

最终结果应该返回如下内容:

    +-----------+-----------+-----+------------+
    | MAX(avg1) | MAX(avg2) | ... | MAX(avg50) |
    +-----------+-----------+-----+------------+
    | ~355      | ~1416     | ... | 634        |
    +-----------+-----------+-----+------------+

现在,我的SQL看起来像这样:

    SELECT MAX(avg1), MAX(avg2), ... , MAX(avg50)
    FROM (
        SELECT ID, AVG(field1) AS avg1, AVG(field2) AS avg2, ... , 
    AVG(field50) AS avg50
        FROM table
        GROUP BY ID
        AS subquery
    )

但是,我在子查询中得到奇怪的语法错误,因为LIMIT语句似乎被添加到子查询的末尾,并且事情搞砸了。我对SQL比较陌生,不确定我当前的方法是不是最好的方法。

如果有人可以通过修复我的代码来帮助我使其工作或提供更好的解决方案,而我不必大量地输入50多个字段的名称,那将非常感激。

如果您需要进一步澄清我正在尝试做什么,请随时发表评论。

由于

1 个答案:

答案 0 :(得分:1)

您的语法错误将AS subquery放在内部查询之外,如下所示

SELECT MAX(avg1), MAX(avg2), ... , MAX(avg50)
    FROM (
        SELECT ID, AVG(field1) AS avg1, AVG(field2) AS avg2, ... , 
    AVG(field50) AS avg50
        FROM table
        GROUP BY ID
    ) AS subquery