MySQL SQL - 将列中的值相加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9334686/
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
SQL- Add up Values in a Column
提问by cmorris1441
How can I add up values in a SQL column? I have the table set up in xampp and I'm trying to add up all the values in a column titled "gross".
如何将 SQL 列中的值相加?我在 xampp 中设置了表格,我正在尝试将标题为“gross”的列中的所有值相加。
回答by Brian Webster
SQL Server or MySQL:
SQL Server 或 MySQL:
select sum(MyColumn) as MyColumnSum from MyTable
If you need to sum a column by a grouping of another column
如果您需要按另一列的分组对一列求和
select sum(MyColumn) as MyColumnSum, OtherColumn from MyTable Group By OtherColumn
Here is a way to, separately, add up negative or positive numbers
这是一种分别将负数或正数相加的方法
select
sum( case when MyColumn < 0 then MyColumn else 0 end ) as NegativeSum,
sum( case when MyColumn > 0 then MyColumn else 0 end ) as PositiveSum
from
MyTable
Reference
参考
回答by cmorris1441
select sum(yourCol) as Gross
from YourTable
Use the aggregate function SUM().
使用聚合函数 SUM()。
回答by James Hill
Take a look at the SUM()
function documentation for MySQL.
查看SUM()
MySQL的函数文档。
SELECT YourRecordID,
SUM(Gross) AS GrossSum
FROM YourTable
GROUP BY YourRecordID