MySQL从多个列中选择并计算值 [英] MySQL select and calculate value from multiple columns

查看:342
本文介绍了MySQL从多个列中选择并计算值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个mysql选择查询,该查询会基于其他两个字段来计算值.

I am trying to create a mysql select query of which calculates a value based on two other fields.

这是我的查询

SELECT request_id, (
unit_cost * quantity
) AS claim_value
FROM  `xx_non_part_usage` 
WHERE request_id = request_id
GROUP BY request_id

上面的查询仅返回其中一行的total_value.

The query above only brings back the total_value for one of the rows.

例如-这是一些示例数据,

For example - here is some sample data,

ID      REQUEST_ID      QUANTITY        UNIT_VALUE
1       10001           2.0             3.00
2       10001           1.0             19.00
3       10003           0.5             18.00
4       10001           10.0            12.00
5       10003           0.75            6.76
6       10002           9.0             3.20
7       10001           0.10            13.80
8       10001           1.0             90.99
9       10004           6.75            3.00
10      10009           3.23            87.00 

如您所见,REQUEST_ID为"10001"的几行.查询需要执行的操作是REQUEST_ID * QUANTITY,然后将它们分组,以便仅返回最终价格(将乘积之和(REQUEST_ID * QUANTITY)的所有结果相加.

As you can see there are several rows of REQUEST_ID '10001'. What the query needs to do is REQUEST_ID * QUANTITY then group them so it only returns the final value price (adding all of the results from the multiply sum (REQUEST_ID * QUANTITY).

这是我希望得到的预期结果(REQUEST_ID 10003的不同示例,

Here is an expected result of what I am hoping to get (different example on REQUEST_ID 10003,

REQUEST_ID      TOTAL_VALUE
10003           14.07
10004           20.75
...
...

谢谢.

推荐答案

为什么使用"where"子句?

Why do you use "where" clause?

mysql> select * from test;
+------------+------------+----------+
| request_id | unit_value | quantity |
+------------+------------+----------+
|          1 |          3 |        2 |
|          1 |         19 |        1 |
|          2 |       6.76 |     0.75 |
|          2 |         18 |      0.5 |
+------------+------------+----------+
4 rows in set (0.00 sec)

mysql> SELECT request_id, sum(unit_value * quantity) as x from test group by request_id;
+------------+--------------------+
| request_id | x                  |
+------------+--------------------+
|          1 |                 25 |
|          2 | 14.070000171661377 |
+------------+--------------------+
2 rows in set (0.00 sec)

这篇关于MySQL从多个列中选择并计算值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆