如何(MySQL)乘以列然后求和行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17806545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:16:28 来源:igfitidea点击:
How to (MySQL) multiply columns and then the sum rows?
提问by trafalgar
I've got this table:
我有这张桌子:
id | payment_id | quantity | unit cost
1 633 1 750
2 633 1 750
3 632 2 750
4 632 2 750
What I need is :
我需要的是:
payemnt_id | total
633 1500
632 3000
You can also think of this as Countries and then you are trying to find the total for each Country. I was sure there were some tutorials like this but could not find by STFW.
您也可以将其视为国家,然后您试图找到每个国家的总数。我确信有一些这样的教程,但 STFW 找不到。
回答by lc.
You can simply put the formula (expression) inside SUM
:
你可以简单地把公式(表达式)放在里面SUM
:
SELECT payment_id, SUM(`unit cost` * quantity) AS total
FROM myTable
GROUP BY payment_id
回答by Maxim Zhukov
SELECT payemnt_id, SUM(`unit cost` * quantity) as total
FROM Table1
GROUP BY payemnt_id
回答by AmazingDreams
SELECT
payment_id,
SUM(subtotal) AS total
FROM(
SELECT
payment_id,
(unit_cost * quantity) AS subtotal
) AS t1
GROUP BY
payment_id