2016-03-21 46 views
1

這是我的表MySQL的 - 從總和()和其中一個表中選擇條款

|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 | 

它如何能做到這一點?在此先感謝:)

回答

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 
+0

好吧,它的工作原理!非常感謝 :) –

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找出哪些變體是可取的

相關問題