这是我的表
expiration_interval
我想将行的总和结果与(01,03,05)中的代码显示为借方,将(02,04,06)显示为贷方, 所以结果看起来像这样
|id | code | amount |
----------------------
|1 | 01 | 500 |
|2 | 02 | 2500 |
|3 | 03 | 700 |
|4 | 04 | 500 |
|5 | 05 | 500 |
|6 | 06 | 500 |
它怎么能这样做?提前谢谢:)
答案 0 :(得分:5)
一种选择是使用conditional aggregation
:
select
sum(case when code in ('01','03','05') then amount end) debit,
sum(case when code in ('02','04','06') then amount end) credit
from yourtable
答案 1 :(得分:0)
另一种变体,有时候条件聚合可能更好:
select sum(debit), sum(credit) from
(
select sum(amount) as debit, 0 as credit
from table where code in ('01','03','05')
union all
select 0, sum(amount)
from table where code in ('02','04','06')
) as q
实际性能取决于表结构/大小/索引,因此运行explain
以确定哪种变体更可取