0

我有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_Balancenegative然后将使用 Php 处理结果。

更新: 我曾经对交易金额进行过这种处理:我总结了所有Transaction_Amount基于他们的Transaction_Name

IE

余额 = (All Transaction_Name 'SALES')减去 (-) (All Transaction_Name 'PAYMENT')

但这将迫使我创建虚拟表作为我的报告的存储库表和更多的 php 条件来比较和插入。

4

3 回答 3

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 表,因为我们没有在任何地方使用 Customer Name。

于 2013-02-26T02:23:59.210 回答
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
于 2013-02-25T12:57:15.997 回答
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

第一个子查询汇总每个客户的所有正值,而第二个子查询汇总所有负值。然后您获取所有客户并将两个对应的值组合成一个结果。

于 2013-02-25T12:46:54.860 回答