SQL: How to to SUM two values from different table

2019-02-04 06:46发布

Okay.

I've been put on a project at work, and though I've got some SQL skills, they are very rusty.

One of the scenarios at work has left me with a number of tables with values I need to sum up. They are not linked either, but the order is the same across all the tables.

Basically, I would like to take this two tables:

CASH TABLE  
London  540
France  240
Belgium 340

CHEQUE TABLE
London  780
France  490
Belgium 230

To get an output like this to feed into a graphing application:

London  1320
France  730
Belgium 570

Please help.

4条回答
相关推荐>>
2楼-- · 2019-02-04 07:11
select region,sum(number) total
from
(
    select region,number
    from cash_table
    union all
    select region,number
    from cheque_table
) t
group by region
查看更多
劳资没心,怎么记你
3楼-- · 2019-02-04 07:26
SELECT (SELECT SUM(London) FROM CASH) + (SELECT SUM(London) FROM CHEQUE) as result

'And so on and so forth.

查看更多
手持菜刀,她持情操
4楼-- · 2019-02-04 07:27

you can also try this in sql-server !!

select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city 

demo

or try using sum,union

select sum(total)  as mytotal,city
from
(
    select * from cash union
    select * from cheque
) as vij
group by city 
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-02-04 07:29

For your current structure, you could also try the following:

select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country

I think I prefer a union between the two tables, and a group by on the country name as mentioned above.

But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)

查看更多
登录 后发表回答