简体   繁体   English

每个ID的MySQL总和,不包含子查询

[英]MySQL sum per IDs without subqueries

I'm working on a huge dataset, with a table that looks like this : 我正在处理一个巨大的数据集,其表如下所示:

+----+---------+--------+--------+
| id | otherid | value1 | value2 |
+----+---------+--------+--------+
|  1 |       1 |      2 |      5 |
|  1 |       1 |      4 |      8 |
|  1 |       2 |      3 |      6 |
|  2 |     123 |      1 |      4 |
+----+---------+--------+--------+

I need to multiply value1 and value2 for each row, and sum values per id and otherid. 我需要将每行的value1和value2相乘,并将每个id和otherid的值相加。 A result table might be: 结果表可能是:

+----+---------+-----+
| id | otherid | sum |
+----+---------+-----+
|  1 |       1 |  42 | ((2*5)+(4*8))
|  1 |       2 |  18 | (3*6)
|  2 |     123 |   4 | (1*4)
+----+---------+-----+

My question is if it is possible to avoid subqueries to do this, I only found solutions that used them. 我的问题是,是否有可能避免子查询这样做,我只找到了使用它们的解决方案。

Thanks! 谢谢!

it's easy. 这很容易。

  SELECT id,  
         otherid, 
         SUM(value1*value2) AS sum
    FROM your_table
GROUP BY id, otherid;

Try Below Query 尝试以下查询

SELECT ID,otherid ,SUM(value1  * value2) sum 
FROM TABLE1
GROUP BY ID,otherid

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

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