我有许多需要汇总的表格数值,它们没有关联,但在所有表格中顺序都是相同的。
基本上,我想将这两个表格:
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
UNION
本身将删除非唯一(重复)行。UNION ALL
将保留联合中的所有行,使总和准确。 - HarrisonSELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result
'等等,诸如此类。'
“COALESCE函数的基本作用是说:“返回第一个参数,除非它为null,在这种情况下返回第二个参数”-在这些场景中非常实用。”来源
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和Name,以及一个付款表,其中包含: CountryId(外键指向国家),Total,Type(现金/支票)
UNION
、GROUP BY
和SUM
会很有用。 - zero323