SQL: How to to SUM two values from different tables [closed]

我的未来我决定 提交于 2019-11-27 13:03:09

问题


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.


回答1:


select region,sum(number) total
from
(
    select region,number
    from cash_table
    union all
    select region,number
    from cheque_table
) t
group by region



回答2:


SELECT (SELECT SUM(London) FROM CASH) + (SELECT SUM(London) FROM CHEQUE) as result

'And so on and so forth.




回答3:


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 



回答4:


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)



来源:https://stackoverflow.com/questions/19436895/sql-how-to-to-sum-two-values-from-different-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!