0

我想在我的网页上显示以下信息:
日期 - 个人费用(业务费用)
06-June-2012 - usd555.00 (usd3022.00)
05-June-2012 - usd666.00 (usd0.00)
04-June -2012 - usd0.00 (usd444.40)
04-June-2012 - usd333.00 (usd2333.40)

目前我的代码是:

$sql = "SELECT payment_date, sum(price) FROM expense WHERE category=? spender_id=? GROUP BY payment_date";
    $q = $conn->prepare($sql);
    $result = $q->execute(array("Personal", $user_id));
    while($r = $q->fetch(PDO::FETCH_ASSOC)){
        $payment_date_db = $r['payment_date'];
        $payment_date_db2 = date("d-F-Y", strtotime($payment_date_db));
        $price_db = $r['sum(price)'];

        echo $payment_date_db2 . " - " . $money_currency . $price_db . "<br />";
    }

我不知道如何选择和显示业务费用记录并将其显示到总括符号()中。任何的想法?

4

1 回答 1

1

您确实应该提供有关表架构的更多详细信息,但我想我可以从您的查询中推断出它是这样的:

费用(payment_id [PK],spender_id [FK],类别 [FK??],价格,payment_date)

其中类别字段包含“个人”或“费用”。

因此,如果您想获取特定消费者在每个日期的个人和业务费用的总和,请尝试以下查询:

SELECT 
    payment_date,
    SUM(IF(category = 'Personal', price, 0)) AS personal_expense_total,
    SUM(IF(category = 'Business', price, 0)) AS business_expense_total
FROM 
    expense
WHERE 
    spender_id = ?
GROUP BY 
    payment_date

所以在你的 PHP 代码中,你可以这样做:

$sql = '
    SELECT
        payment_date,
        SUM(IF(category = "Personal", price, 0)) AS personal_expense_total,
        SUM(IF(category = "Business", price, 0)) AS business_expense_total
    FROM expense
    WHERE spender_id = :spender_id
    GROUP BY payment_date';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':spender_id', $user_id, PDO::PARAM_INT); // Assuming $user_id contains an integer
$stmt->execute();

while($r = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $date = date('d-F-Y', strtotime($r['payment_date']));
    $personal = 'usd' . number_format($r['personal_expense_total'], 2);
    $business = 'usd' . number_format($r['business_expense_total'], 2);

    echo "$date - $personal - ($business)<br />";
}
于 2012-06-10T18:50:17.537 回答