如何计算mysql中多个条件值的总和
Posted
技术标签:
【中文标题】如何计算mysql中多个条件值的总和【英文标题】:how to calculate of sum of multiple conditional values in mysql 【发布时间】:2021-03-18 07:05:24 【问题描述】:我正在尝试获取条件值的总和并按分钟分组。
我成功完成了以下查询,但结果需要一些时间,想知道有什么有效的方法吗?
SELECT x.query, x.value, x.time FROM (
SELECT id, query, SUM(VALUE) AS value, time FROM `modbuslogs` WHERE query IN ("sensor1","sensor2") AND time LIKE '2020-12-04%' GROUP BY HOUR(time), MINUTE(TIME)
UNION
SELECT id, query, SUM(VALUE) AS value, time FROM `modbuslogs` WHERE query IN ("sensor3","sensor4") AND time LIKE '2020-12-04%' GROUP BY HOUR(time), MINUTE(TIME)
) x
GROUP BY x.query, HOUR(time), MINUTE(TIME)
ORDER BY x.id
表结构:
+--------+-------+-----------------+
| query | value | time |
+--------+-------+-----------------+
|sensor1 | 2 |2012-02-10 00:00 |
|sensor2 | 2 |2012-02-10 00:00 |
|sensor3 | 3 |2012-02-10 00:00 |
|sensor4 | 3 |2012-02-10 00:00 |
|sensor1 | 2 |2012-02-10 00:01 |
|sensor2 | 3 |2012-02-10 00:01 |
|sensor3 | 3 |2012-02-10 00:01 |
|sensor4 | 2 |2012-02-10 00:01 |
+--------+-------+-----------------+
获得和预期的输出:
+--------+-------+-----------------+
| query | value | time |
+--------+-------+-----------------+
|sensor1 | 4 |2012-02-10 00:00 |
|sensor3 | 6 |2012-02-10 00:00 |
|sensor1 | 5 |2012-02-10 00:01 |
|sensor3 | 5 |2012-02-10 00:01 |
+--------+-------+-----------------+
【问题讨论】:
【参考方案1】:首先,union
子查询毫无意义。这相当于您的查询:
select id, query, sum(value) as value, min(time) as time
from modbuslogs
where
query in ('sensor1', 'sensor2', 'sensor3', 'sensor4')
and time >= '2020-12-04'
and time < '2020-12-05'
group by query, hour(time), minute(time)
这为每 query
和每分钟提供一行,总和为 value
。并不是说我们需要围绕time
的聚合函数,所以select
子句与group by
子句是一致的。此外,where
子句使用日期过滤而不是字符串匹配。
另一方面,如果您希望将两组传感器放在两个不同的列中,则使用条件聚合:
select id, min(time) as time,
sum(case when query in ('sensor1', 'sensor2') then value else 0 end) as value_1_2,
sum(case when query in ('sensor3', 'sensor4') then value else 0 end) as value_3_4
from modbuslogs
where
query in ('sensor1', 'sensor2', 'sensor3', 'sensor4')
and time >= '2020-12-04'
and time < '2020-12-05'
group by hour(time), minute(time)
【讨论】:
我使用了您的第二个查询。好极了。非常感谢以上是关于如何计算mysql中多个条件值的总和的主要内容,如果未能解决你的问题,请参考以下文章
你会如何解决这个问题?使用reduce方法计算此数组中嵌套对象值的总和?