0

认为我的问题是我试图在同一个查询中求和一个计数,这可以在 php 中实现以避免这种情况吗?Records 列显示记录数,而 Costs 对成本求和,这很好用,但我想然后对这两个列进行求和以显示总计?

Select
  tblcontacts.ContactFullName As Name,
  Count(tblcases.CaseID)As Records,
  Sum(tblcases.CaseCommission) As Costs
From
  tblcontacts Inner Join
  tblcases On tblcontacts.ContactID =
    tblcases.ContactAssignedTo
Group By
  tblcontacts.ContactFullName
4

3 回答 3

4

如果不添加另一个查询并执行UNION其中一个查询,则无法在 MySQL 中执行此操作,例如:

Select
  tblcontacts.ContactFullName As Name,
  Count(tblcases.CaseID)As Records,
  Sum(tblcases.CaseCommission) As Costs
From
  tblcontacts Inner Join
  tblcases On tblcontacts.ContactID =
    tblcases.ContactAssignedTo
Group By
  tblcontacts.ContactFullName

UNION ALL

Select
  '--GRAND-TOTAL--',
  Count(tblcases.CaseID),
  Sum(tblcases.CaseCommission)
From
  tblcontacts Inner Join
  tblcases On tblcontacts.ContactID =
    tblcases.ContactAssignedTo

然而,在这种情况下,在 PHP 中计算总计可能会获得更好的性能,可能同时迭代行以构建表。

于 2012-06-29T12:50:42.190 回答
3

最后使用With RollUp。单次扫描表,所以它是面向性能的。

Select
  tblcontacts.ContactFullName As Name,
  Count(tblcases.CaseID)As Records,
  Sum(tblcases.CaseCommission) As Costs
From
  tblcontacts Inner Join
  tblcases On tblcontacts.ContactID =
    tblcases.ContactAssignedTo
Group By
  tblcontacts.ContactFullName
WITH RollUP

请参阅此处了解更多详情

于 2012-06-29T13:20:14.083 回答
0

如果您在 PHP 中循环显示要显示的结果集,则可以在循环时对列求和。

例如

$sql = "your SQL here";

$query = mysql_query($sql);

$sum_records = $sum_costs = 0;

while ($r = mysql_fetch_object($query))
{
    // your other code here for whatever you're doing with the results
    $sum_records += $r->Records;
    $sum_costs += $r->Costs; 
}

// Now you have the two totals in $sum_records and $sum_costs.
于 2012-06-29T13:09:04.973 回答