我有两个表,客户端和事务,我试图在同一行显示来自同一客户端的所有事务的SUM和COUNT,以及交易的类型,但我不知道如何对它进行分组,因此它只显示一个客户端的总数,而下一行是另一个客户端的总数,而不是重复它。感谢您的时间。
表客户
id_client - client_name
表交易
id_transaction - client_id - date - type - amount
&approx_contour[0]
答案 0 :(得分: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; "
注意:我没有修复"交易错误#34;在你的查询中,因为我不确定它是否是一个错字或你的表实际上有这个名字。