我有 2 数据库表:客户信息和余额
客户:Customer_ID,名称
交易:Customer_ID,Transaction_Name,Transaction_Amount ... (其他列但我的问题不是必需的)
示例预期查询输出:
Customer_ID | Debit_Balance | Credit_Balance
1 | 500.00|
2 | | 300.00
说明:客户1的剩余余额为500.00,客户2的额外金额为300.00 (通常为( - )负数)
问题:
如何单独在单个查询中执行此操作?我只是想生成报告(如上面的示例输出),以显示结果金额如果 positive
作为Debit_Balance和Credit_Balance用于那些negative
余额然后将使用Php。
更新
我曾经对交易金额进行处理:我根据Transaction_Amount
总结所有Transaction_Name
。
即。
余额=(所有Transaction_Name'销售')更少( - )(全部 Transaction_Name'PAYMENT')
但是这将迫使我创建虚拟表作为我的报告的存储库表和更多的php条件来比较和插入。
答案 0 :(得分:1)
我会使用类似下面的内容:
SELECT C.customer_id, C.Name,
IF(SUM(Transaction_Amount)>0, SUM(Transaction_Amount),'') as Debit_Balance,
IF(SUM(Transaction_Amount)<=0, SUM(Transaction_Amount),'') as Credit_Balance
From Customer As C
LEFT JOIN Transaction As T ON C.customer_id = T.customer_id
GROUP BY T.customer_id
答案 1 :(得分:1)
您希望每个客户都有一行输出,余额分为一列或另一列,具体取决于它是正还是负。尝试(如果我们使用标准SQL):
select
subqry.Customer_ID
, case
when subqry.Balance >= 0 then subqry.Balance
end as Debit_Balance
, case
when subqry.Balance < 0 then subqry.Balance * -1
end as Credit_Balance
from (
select
Customer_ID
, sum(
case Transaction_Name
when 'SALES' then Transaction_Amount
when 'PAYMENT' then Transaction_Amount * -1
else null
end
) as Balance
from Transaction
group by Customer_ID
) as subqry
到目前为止,无需加入Customer表,因为我们没有在任何地方使用客户名称。
答案 2 :(得分:0)
我无法想出比这更容易的事情:
SELECT c.customer_id, pos.amount debit_balance, neg.amount credit_balance
FROM customer c
LEFT JOIN (SELECT SUM(t.transaction_amount) amount, t.customer_id
FROM transaction t
WHERE t.transaction_amount > 0
GROUP BY t.customer_id) pos ON pos.customer_id = c.customer_id
LEFT JOIN (SELECT SUM(t2.transaction_amount) amount, t2.customer_id
FROM transaction t2
WHERE t2.transaction_amount < 0
GROUP BY t2.customer_id) neg ON neg.customer_id = c.customer_id
第一个子查询总结了每个客户的所有正值,而第二个子查询总结了所有负值。然后,您将获得所有客户,并将两个相应的值组合成一个结果。