【问题标题】:how to get sum and count from this result set?如何从此结果集中获取总和和计数?
【发布时间】:2012-03-28 13:43:30
【问题描述】:

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

知道如何循环结果集以获取匹配收集器的总和,同时获取计数并将结果放入新数组吗?

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      SELECT collector,sum(amount) as amount,COUNT(*) as count,name
      FROM Table
      GROUP BY  collector,name;
      

      【讨论】:

        【解决方案3】:

        使用 SUM 和 COUNT 获得直接结果。不需要循环。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-12-16
          • 2021-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-14
          相关资源
          最近更新 更多