问题
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