我有一些表格,需要将其数值相加。它们也没有连接起来,但所有表的顺序都是一样的。
基本上,我想把这两个表。
CASH TABLE
London 540
France 240
Belgium 340
CHEQUE TABLE
London 780
France 490
Belgium 230
把这两张表输出到图形程序中去
London 1320
France 730
Belgium 570
select region,sum(number) total
from
(
select region,number
from cash_table
union all
select region,number
from cheque_table
) t
group by region
SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result
'等等等等。
"COALESCE函数基本上说 "返回第一个参数,除非它是null,在这种情况下,返回第二个参数"--在这些场景下,它相当方便。" 来源
你也可以在sql-server中试试这个!
select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city
或者尝试使用sum,union
select sum(total) as mytotal,city
from
(
select * from cash union
select * from cheque
) as vij
group by city
对于你目前的结构,你也可以尝试以下方式。
select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country
我想我更倾向于两张表之间的联合,以及上面提到的按国家名称分组。
但我也建议将你的表标准化。理想的情况是,你会有一个国家表,有Id和名称,还有一个付款表:CountryId(FK到国家),Total,Type(现金支票)。