简体   繁体   中英

mysql - select from a table with sum() and where clause

this is my table

|id | code | amount |
----------------------
|1  |  01  | 500    | 
|2  |  02  | 2500   | 
|3  |  03  | 700    | 
|4  |  04  | 500    | 
|5  |  05  | 500    | 
|6  |  06  | 500    | 

i want to show the sum results of row with the code in (01,03,05) as debit and (02,04,06) as credit, so the result would look like this

|id | code | debit  | credit |
------------------------------
|   |      | 1700   | 3500   |

how can it do that ? thanks in advance :)

One option is to use 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

another variant, which sometimes could be better neither conditional aggregation:

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

actual performance depends on table structure/size/indexes, so run explain to figure out what variant is preferable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM