如何从这个结果集中得到总和和计数?

时间:2012-03-28 13:43:31

标签: php mysql codeigniter

Mysql查询返回像这样的结果

collector amount    name
1     0.00      gihan
1     2000.00   gihan
1     2500.00   gihan
1     11502.00  gihan
2     1140.00   lasita

我希望得到像

这样的结果数组
collector  amount  count  name
1         16002.00   4    gihan
2          1140.00   1    lasita

任何想法如何循环结果集以获得匹配收集器的总和并且同时获取计数并将结果放入新数组中?

3 个答案:

答案 0 :(得分:3)

为什么要在PHP中解决这个问题,当你可以让MySQL为你工作时?

SELECT collector, sum(amount) as amount, count(*) as `count`, name 
FROM yourTable
GROUP BY collector, name

答案 1 :(得分:1)

SELECT collector,sum(amount) as amount,COUNT(*) as count,name
FROM Table
GROUP BY  collector,name;

答案 2 :(得分:1)

使用SUM和COUNT来获得直接结果。没有必要的循环。

SELECT Collector,SUM(Amount) as Amount,COUNT(Amount) as Count,Name
FROM YourTable
GROUP BY Collector,Name