我需要结合3个求和查询的结果并在循环中回显结果。我坚持认为这是如何以正确的方式完成的。我想使用while循环为每个客户端回显一行,显示按客户端名称分组的3个求和查询的结果:
客户名称|总到期|现金销售总额|信贷销售总额
结果显示所有由于客户端。 noncashresult显示所有由于来自Credit销售的客户。 cashresult显示全部由于来自现金销售的客户。
$result = mysql_query("SELECT `client_name` As `Client`, SUM(`due_to_client`) As `Total Due`
FROM `Consignment`
WHERE `payout_approved` = 'Yes'
GROUP BY `client_name`");
$noncashresult = mysql_query("SELECT `client_name` As `Client`, SUM(`due_to_client`) As `Credit Total Due`
FROM `Consignment`
WHERE `payout_approved` = 'Yes' AND `paymenttype` IN ('Credit')
GROUP BY `client_name`");
$cashresult = mysql_query("SELECT `client_name` As `Client`, SUM(`due_to_client`) As `Cash Total Due`
FROM `Consignment`
WHERE `payout_approved` = 'Yes' AND `paymenttype` IN ('Cash')
GROUP BY `client_name`");
while($row = mysql_fetch_array($result))
{
echo $row['Client'];
echo $row['Total Due'];
echo $row['Credit Total Due'];
echo $row['Cash Total Due'];
}
答案 0 :(得分:3)
您可以使用以下内容:
SELECT `client_name` As `Client`,
SUM(`due_to_client`) As `Total Due`,
SUM(CASE WHEN `paymenttype`='Credit' THEN `due_to_client` ELSE 0 END) As `Credit Total Due`,
SUM(CASE WHEN `paymenttype`='Cash' THEN `due_to_client` ELSE 0 END) As `Cash Total Due`
FROM `Consignment`
WHERE `payout_approved` = 'Yes'
GROUP BY `client_name`
这应该产生结果:
Client | Total Due | Credit Total Due | Cash Total Due
当然,尽量避免使用mysql_ *扩展,而在mysql 5.5.x中不推荐使用它。而是使用mysqli或pdo扩展