假设我有一个帐户条目移动表,比如
FrmEnv.Show
我想对信用额度和借记行总和进行分组,并在不同的列中显示它们的每个总和。
我试图做的是总结各方的平衡,比如
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
我获得 2 行,一个用于借记金额,另一个用于贷记金额,例如
select title, side, sum(balance) from accounts group by side
+-------+------+---------+
| cash | debit| 500.0 |
+-------+------+---------+
| cash |credit| 900.0 |
+-------+------+---------+
感谢。
答案 0 :(得分: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
答案 1 :(得分: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;