2011-01-06 24 views
1

我有我的表这个数据(tb_cash_transaction)MySQL的3组通过与和

alt text

我想组类型列,CURRENCY_ID柱和金额列,因此这将成为象下面这样:

**Currency** **Cash IN** **Cash OUT** **Balance** 

14    40000  30000  10000   
15    50000  40000  10000 

规则:

1.Group通过货币
2.然后找到的现金总和为货币
3.Find的现金总和从该货币
4.Get余额(金额现金 - 现金和出)

如何使用MySQL来实现呢?我尝试使用group by,但无法获得所需的输出。

在此先感谢

回答

4
SELECT currency_id, 
     SUM(CASE 
      WHEN TYPE = 'cash_in' THEN amount 
      END) AS cash_in, 
     SUM(CASE 
      WHEN TYPE = 'cash_out' THEN amount 
      END) AS cash_out, 
     SUM(CASE 
      WHEN TYPE = 'cash_in' THEN amount 
      ELSE -amount 
      END) AS balance 
FROM tb_cash_transaction 
WHERE TYPE IN ('cash_in', 'cash_out') /*<--- Where clause probably not needed 
             but just in case there are other options*/ 
GROUP BY currency_id 
+0

此查询工作得很好,也更简单。谢谢:) – cyberfly 2011-01-06 03:55:31

+0

@cyberfly - 它只是让一个通过数据,所以我会认为它应该比自己更有效的联接方式。 – 2011-01-06 03:58:19

0

试试这个:

SELECT a.currency_id, cash_in, cash_out, (cash_in - cash_out) balance 
    FROM (
       SELECT currency_id, SUM(AMOUNT) cash_in 
        FROM tb_cash_transaction 
       WHERE type = 'cash_in' 
       GROUP BY currency_id 
       ) a, 
       (
       SELECT currency_id, SUM(AMOUNT) cash_out 
        FROM tb_cash_transaction 
       WHERE type = 'cash_out' 
       GROUP BY currency_id 
       ) b 
    WHERE a.currency_id = b.currency_id 
0
select currency_id, cashin "Cash In", cashout "Cash Out", 
cashin-cashout "Balance" from (
    select currency_id, sum(if(type='cash_in',amount,0)) as cashin, 
    sum(if(type='cash_out',amount,0)) as cashout, 
    from tb_cash_transaction group by currency_id 
) 
0

这里是我使用的解决方案。感谢cybernate代码。

SELECT a.currency_id, cashin, cashout, (cashin - cashout) balance 
FROM (
      SELECT currency_id, SUM(AMOUNT) cashin 
      FROM tb_cash_transaction 
      WHERE type = 'cash_in' 
      GROUP BY currency_id 
      ) a, 
      (
      SELECT currency_id, SUM(AMOUNT) cashout 
      FROM tb_cash_transaction 
      WHERE type = 'cash_out' 
      GROUP BY currency_id 
      ) b 
WHERE a.currency_id = b.currency_id