Mysql:根据两个查询减去值

时间:2012-06-15 06:27:09

标签: mysql

我有以下两个问题。

SELECT 
    account_name,SUM(amount) AS AMOUNT1 
FROM 
    entries 
LEFT JOIN 
    accounts ON accounts.id = entries.accounts_id
WHERE 
    side = 'D' AND op_balance_dc = 'D'
GROUP BY 
    accounts.id

以下是查询结果:

Query1

SELECT 
    account_name,SUM(amount) AS AMOUNT2 
FROM 
    entries 
LEFT JOIN 
    accounts ON accounts.id = entries.accounts_id
WHERE 
    side = 'C' AND op_balance_dc = 'D'
GROUP BY 
    accounts.id

这是第二个查询的结果

Query2

我没有尝试显示上述两个查询的结果,我想要实现的是从上面的查询中获取account_name,AMOUNT1和AMOUNT2然后从Amount2 FROM AMOUNT1中减去 - 然后从我的表中添加一个值柱。

示例:

(AMOUNT1-AMOUNT2)+op_balance  //here op_balance is my column name

然后显示account_name(AMOUNT1-AMOUNT2)+op_balance

你能帮我解决一下这个问题吗?

谢谢:)

如果您需要更多信息,请与我们联系。:)

被修改

这是我的表格的结构:

谢谢:)

EDIT2

表名:条目(案例-1)

  id    trans_id   accounts_id    amount    side
   1      1       12               1000      D
   2      1        1               1000      C
   7      4        1              14000      D
   8      4        2              14000      C

表名:条目(案例-2)

  id    trans_id   accounts_id  amount        side
  1           1       12          1000       D
  2           1        1          1000       C

您的代码适用于案例1,但不适用于案例2。您在代码中使用了lentries.accounts_id = entries.accounts_id,这就是为什么表中的同一accounts_id没有多个值可以加入,而且您的代码不计算case-2中的值。

但我正在尝试获取所有数据。谢谢:))

2 个答案:

答案 0 :(得分:2)

SELECT
    a.account_name,
    a.AMOUNT1,
    b.AMOUNT2,
    (a.AMOUNT1 - COALESCE(b.AMOUNT2, 0)) + a.op_balance AS calculated
FROM
    (
        SELECT accounts.id, account_name, SUM(amount) AS AMOUNT1, op_balance
        FROM entries 
        LEFT JOIN accounts ON accounts.id = entries.accounts_id
        WHERE side='D' AND op_balance_dc='D'
        GROUP BY accounts.id
    ) a
LEFT JOIN
    (
        SELECT accounts.id, SUM(amount) AS AMOUNT2 FROM entries 
        LEFT JOIN accounts ON accounts.id = entries.accounts_id
        WHERE side='C' AND op_balance_dc='D'
        GROUP BY accounts.id
    ) b ON a.id = b.id
GROUP BY
    a.id

答案 1 :(得分:2)

以下是所有帐户的EDITED QUERY

select
  a.id,
  a.account_name,
  a.op_balance,
  ifnull(e.AMOUNT1,0) as Amount1,
  ifnull(l.AMOUNT2,0) as Amount2,
  ((ifnull(SUM(e.AMOUNT1),0)-ifnull(l.AMOUNT2,0))+a.op_balance) as Balance
from accounts a
  left join (SELECT
               accounts_id,
               SUM(amount)     AS AMOUNT1
             FROM entries
               LEFT JOIN accounts
                 ON accounts.id = entries.accounts_id
             WHERE entries.side = 'D'
                 AND accounts.op_balance_dc = 'D'
             GROUP BY accounts.id) as e
    on e.accounts_id = a.id
  left join (SELECT
               accounts_id,
               SUM(amount)     AS AMOUNT2
             FROM entries
               LEFT JOIN accounts
                 ON accounts.id = entries.accounts_id
             WHERE side = 'C'
                 AND op_balance_dc = 'D'
             GROUP BY accounts.id) as l
    on l.accounts_id = a.id
group by a.id