mysql 获取字段值总和
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 获取字段值总和相关的知识,希望对你有一定的参考价值。
$sql ="select sum(dingdan_price) from dingdan";
$re = mysql_query($sql);
var_dump($re);
为什么打印的结果是resource(5) of type (mysql result)
我有个dingdan表 然后dingdan_price里边存的是每条订单记录卖的金额
想把所有记录的金额相加
$re = mysql_query($sql);
list($sum)=mysql_fetch_row($re);
mysql_free_result($re);
echo "总和=$sum"; 参考技术A select sum(line) from dx_member
呃,既然解决了,就多加一句,有什么SQL语句的问题可以参考这个网站,
http://www.w3school.com.cn/sql/index.asp
如何计算mysql中多个条件值的总和
【中文标题】如何计算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 获取字段值总和的主要内容,如果未能解决你的问题,请参考以下文章