![](/img/trans.png)
[英]Select from four mysql table with count and sum columns and where clause
[英]mysql - select from a table with sum() and where clause
這是我的桌子
|id | code | amount |
----------------------
|1 | 01 | 500 |
|2 | 02 | 2500 |
|3 | 03 | 700 |
|4 | 04 | 500 |
|5 | 05 | 500 |
|6 | 06 | 500 |
我想顯示以(01,03,05)中的代碼作為借方和(02,04,06)作為貸方的行的總和結果,因此結果看起來像這樣
|id | code | debit | credit |
------------------------------
| | | 1700 | 3500 |
怎么辦呢? 提前致謝 :)
一種選擇是使用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
另一種變體,有時既沒有條件聚合也可能更好:
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
以找出更合適的變體
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.