我如何计算和汇总数据库中的值

时间:2010-09-13 06:54:34

标签: php mysql

我在mysql中有一个表,它以整数形式保存值,我的表是这样的。

alt text

我想总结某个特定列的值,例如我想计算总金额,现金支付总额和总余额。我能做到吗?

5 个答案:

答案 0 :(得分:4)

使用MySQL的SUM()功能:

select SUM(amount) from tablename;
select SUM(cashpaid) from tablename;
select SUM(balance) from tablename;

或者您可以将它们分组为一个:

select SUM(amount), SUM(cashpaid), SUM(balance) from tablename;

答案 1 :(得分:2)

如果您想在一个查询中执行此操作:

SELECT SUM(amount) as total_amount, SUM(cashpaid) as total_paid,SUM(balance) as total_balance FROM tablename;

计算元素使用COUNT()

SELECT COUNT(*) FROM tablename;

使用此函数时,最好为列名使用别名。

答案 2 :(得分:1)

试试这个:

select SUM(amount) AS total_amount, SUM(cashpaid) AS total_cashpaid, SUM(balance) AS total_balance  from tablename;

答案 3 :(得分:1)

select sum(amount), sum(cashpaid), sum(balance) from tablename

答案 4 :(得分:1)

使用count()函数计算记录总数。

像:

select count(amount) from table_name;

它将从您问题3中的上表返回。

用于SUM()查询中的总和SELECT。 像:

select SUM(amount) as total_amount,SUM(cashpaid) as total_cash_paid,SUM(balance) as total_balance from table_name;
<{1>之后as是您的新列名,它将在执行查询后自动创建。