【问题标题】:Select SUM and COUNT on same row on PHP and MYSQL在 PHP 和 MYSQL 的同一行上选择 SUM 和 COUNT
【发布时间】:2017-07-21 22:01:54
【问题描述】:

我有两个表,clientstransactions,我试图在同一行显示来自同一客户端的所有事务的 SUM 和 COUNT,并且交易类型,但我不知道如何对其进行分组,因此它只显示一个客户的总数,而在下一行显示另一个客户的总数,而无需重复。感谢您的时间。

客户

id_client - 客户名称

交易

id_transaction - client_id - 日期 - 类型 - 金额

   $query = " SELECT * FROM  transacctions, clients
    WHERE (transacctions.date BETWEEN '$date1' AND '$date2') 
    AND transactions.client_id = clients.id_client 
    AND transactions.type = '$type' ; "


     <th>Client Name</th>
     <th>Transaction Type</th>
     <th>Number of Transactions</th>
     <th>total amount</th>


       $output.='<td>'.$row['client_name'].'</td>';
       $output.='<td>'.$row['type'].'</td>';
       $output.='<td>'.$row['SUM(amount)'].'</td>';
       $output.='<td>'.$row['COUNT(amount)'].'</td>';

【问题讨论】:

标签: php mysql


【解决方案1】:

按客户ID分组,选择交易ID的金额和计数之和:

$query = " SELECT clients.client_name, transacctions.type
SUM(transacctions.amount) AS sum_amount,
COUNT(transacctions.id_transaction) AS transaction_count
FROM  transacctions, clients
WHERE (transacctions.date BETWEEN '$date1' AND '$date2') 
AND transactions.client_id = clients.id_client 
AND transactions.type = '$type' 
GROUP BY clients.id_client; "

或者,建议使用连接。这会给你同样的结果:

$query = " SELECT clients.client_name, transacctions.type
SUM(transacctions.amount) AS sum_amount,
COUNT(transacctions.id_transaction) AS transaction_count
FROM  clients
INNER JOIN transacctions ON transactions.client_id = clients.id_client 
WHERE (transacctions.date BETWEEN '$date1' AND '$date2') 
AND transactions.type = '$type' 
GROUP BY clients.id_client; "

如果您想查看所有客户,包括没有交易的客户,请将INNER JOIN 更改为LEFT JOIN

$query = " SELECT clients.client_name, transacctions.type
SUM(transacctions.amount) AS sum_amount,
COUNT(transacctions.id_transaction) AS transaction_count
FROM  clients
LEFT JOIN transacctions ON transactions.client_id = clients.id_client 
WHERE (transacctions.date BETWEEN '$date1' AND '$date2') 
AND transactions.type = '$type' 
GROUP BY clients.id_client; "

注意:我没有更正您查询中“事务”的拼写错误,因为我不确定这是拼写错误还是您的表实际上具有该名称。

【讨论】:

  • 谢谢,它确实带来了 SUM 和 COUNT,但只有这些值,你知道如何将“client_name”和事务“type”也放在同一行吗?。
  • 只需将它们添加到SELECT。请参阅我的更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-09
  • 2020-10-14
  • 2020-08-28
  • 2021-11-14
  • 2018-12-07
  • 1970-01-01
  • 2018-06-05
相关资源
最近更新 更多