首页 > 解决方案 > 如何按日期分组并同时计算平均值

问题描述

我对此很陌生,所以就这样吧:我正在尝试从 unixtime 转换为日期格式,然后在计算另一列的平均值时按日期分组。这是在 MariaDB 中。

CREATE OR REPLACE
VIEW `history_uint_view` AS select
    `history_uint`.`itemid` AS `itemid`,
    date(from_unixtime(`history_uint`.`clock`)) AS `mydate`,
    AVG(`history_uint`.`value`) AS `value`
from
    `history_uint`
where
((month(from_unixtime(`history_uint`.`clock`)) = month((now() - interval 1 month))) and ((`history_uint`.`value` in (1,
    0))
    and (`history_uint`.`itemid` in (54799, 54810, 54821, 54832, 54843, 54854, 54865, 54876, 54887, 54898, 54909, 54920, 58165, 58226, 59337, 59500, 59503, 59506, 60621, 60624, 60627, 60630, 60633, 60636, 60639, 60642, 60645, 60648, 60651, 60654, 60657, 60660, 60663, 60666, 60669, 60672, 60675, 60678, 60681, 60684, 60687, 60690, 60693, 60696, 60699, 64610)))

    GROUP by 'itemid', 'mydate', 'value'

标签: dategroup-bymariadb

解决方案


当您选择包含没有聚合函数的列的聚合函数(如 AVG)时,您应该在GROUP BY-clause 中列出除具有聚合函数的列之外的所有列。

所以你的 group by 应该是这样的:

GROUP by itemid, mydate

如果您使用单引号(如'itemid'),MariaDB 会将它们视为字符串,而不是列。


推荐阅读