简体   繁体   English

mysql-从带有sum()和where子句的表中选择

[英]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 我想显示以(01,03,05)中的代码作为借方和(02,04,06)作为贷方的行的总和结果,因此结果看起来像这样

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

how can it do that ? 怎么办呢? thanks in advance :) 提前致谢 :)

One option is to use conditional aggregation : 一种选择是使用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 实际性能取决于表的结构/大小/索引,因此请运行explain以找出更合适的变体

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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