2016-08-24 142 views
3

假设我有一个帐户项移动表,就像mysql - 我可以从同一列中选择值并将它们显示在2列结果中吗?

ACCOUNTS table 
+-------+------+---------+ 
| title | side | balance | 
+-------+------+---------+ 
| cash | debit| 500.0 | 
+-------+------+---------+ 
| cash |credit| 300.0 | 
+-------+------+---------+ 
| cash |credit| 600.0 | 
+-------+------+---------+ 
#..... more than 10'000 debit and credit rows 

我想组信用行之和借记行的总和,并显示在不同的列他们的每一笔。

什么,我试图做的是总结在两侧的群体的平衡,就像

select title, side, sum(balance) from accounts group by side 

我得到行,一个为借方金额,另一个是信贷总和,像

+-------+------+---------+ 
| cash | debit| 500.0 | 
+-------+------+---------+ 
| cash |credit| 900.0 | 
+-------+------+---------+ 



我想是获得整个导致一个结果行,德的总和一个字段中的位和另一个字段中的信用总和。我想最终的结果是这样的

+-------+-------+-------+ 
| cash | 500.0 | 900.0 | 
+-------+-------+-------+ 

谢谢。

+1

选择信用额度并将其加入借方或vica的总和? – Jacobr365

+0

@ Jacobr365谢谢。这是我首先想到的,但我做不到。你能给我一个加入同一个表的简单例子! –

回答

4

您可以使用情况

select title, sum(case side when 'debit' then balance else 0 end), 
    sum(case side when 'credit' then balance else 0 end) 
from accounts 
group by title 
+0

看起来像你在那里留下了一个'内部连接'。 –

+0

@JohnBoker ..谢谢..没有内心..只是一个错字.. – scaisEdge

+0

谢谢,这就是我一直在寻找。我无法在SQL W3学校中找到此声明。 'case'语句是一个SQL还是只适用于mysql? –

1

下面是使用子查询的一个例子。比已经提供的CASE语句冗长得多,但是如果你最终拥有多个标题或者想要进行计算,它就会变得非常简单。

SELECT 
    title 
    ,credit.credit_balance 
    ,debit.debit_balance 
    ,(credit.credit_balance - debit.debit_balance) AS net 
FROM 
    (SELECT 
     title, 
     sum(balance) debit_balance 
    FROM accounts 
    WHERE 
     side = 'debit' 
    GROUP BY side) debit 
INNER JOIN (
    SELECT 
     title, 
     sum(balance) debit_balance 
    FROM accounts 
    WHERE 
     side = 'credit' 
    GROUP BY side) credit ON debit.title = credit.title 
GROUP BY 
    title; 
+0

感谢您的时间,我从来没有尝试子查询,但我会尝试它们 –

相关问题