简体   繁体   中英

Combine single values from different select statements using mysql

I have two distinct queries which return single values and I would like to combine them into one single value. See below:

Query 1:

select sum(value)
    from table.trans as transactions
    where country= 'UK' 
    and transactions.from = 'Angela'

Query 2:

select sum(value)
    from table.trans as transactions
    where country= 'UK' 
    and transactions.to= 'Angela'

I now want to get:

 Value from query 1 - Value from query 2  

You can use conditional aggregation:

select sum(case when t.to = 'Angela' then value end) as to_value,
       sum(case when t.from = 'Angela' then value end) as from_value
from table.trans t
where country = 'UK' and 'Angela' in (t.to, t.from);

For the difference:

select sum(case when t.to = 'Angela' then value
                when t.from = 'Angela' then - value
           end) as diff
from table.trans t
where country = 'UK' and 'Angela' in (t.to, t.from);

You can use IF as well

select SUM(if(transactions.from = 'Angela',ifnull(value,0),0)+ if(transactions.to = 'Angela',ifnull(-value,0),0)) diff
    from table.trans as transactions
    where country= 'UK' 
    and  'Angela' in (transactions.from,transactions.to)

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