简体   繁体   English

获取mysql中所有值的总和

[英]Get the sum of all values in mysql

Let's say I have the following table. 假设我有下表。

mysql> desc items;
+---------------+------------------------+------+-----+---------+-------+
| Field         | Type                   | Null | Key | Default | Extra |
+---------------+------------------------+------+-----+---------+-------+
| item_value    | int(11)                | YES  |     | NULL    |       |
| item_quantity | smallint(5)            | YES  |     | NULL    |       |
+---------------+------------------------+------+-----+---------+-------+

The current SQL statement is simple for items with quantity of 1. 对于数量为1的项目,当前的SQL语句很简单。

select sum(item_value) as total_value from items where user_id = ?

If a row has more than 1 quantity, I would like to take that into account when I add up the values for all users. 如果一行中的数量超过1,则在将所有用户的值相加时会考虑到这一点。 Would it be easier to keep track of the total amount per row ( item_quantity * item_value ) or can I do it within a SQL statement? 跟踪每行的总金额( item_quantity * item_value )会更容易,还是可以在SQL语句中完成?

您可以在sum()语句中进行算术运算:

select sum(item_quantity * item_value) as total_value from items where user_id = ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM