[英]Sum of sums in different tables
I have problem with SQL query. 我有SQL查询的问题。
I have tableA: 我有桌子A:
productA priceA
P1 18
P2 35
P1 22
P2 19
and also tableB: 还有tableB:
productB priceB
P1 3
P2 15
P1 80
P2 96
I want as result the sum of two products from the 2 tables. 我希望结果是2个表中的两个产品的总和。
product price
P1 123
P2 165
I want to sum the sums of the two tables. 我想总结两张桌子的总和。
I am trying this query but it's wrong. 我正在尝试这个查询,但这是错误的。
SELECT productA,
(SELECT SUM(priceA) FROM tableA GROUP BY productA),
(SELECT SUM(priceB) FROM tableB GROUP BY productB)
FROM tableA, tableB
WHERE productA = productB
GROUP BY productA
Please help me. 请帮我。
You could use a union
to merge the tables, and group by
on the result: 您可以使用union
来合并表,并对结果进行group by
:
select product
, sum(price)
from (
select productA as product
, priceA as price
from TableA
union all
select productB
, priceB
from TableB
) as SubQueryAlias
group by
product
This is quite literally the sum of sums: 这实际上是总和的总和:
select
product,
sum(price)
from (
select productA as product, sum(priceA) as price from tableA group by 1
union all
select productB, sum(priceB) from tableB group by 1
)
group by 1
Because a join seems like a natural way to approach this problem, here is a solution with join
rather than union
. 因为连接似乎是解决此问题的一种自然方式,所以这是一个使用join
而不是union
的解决方案。 It aggregates the data in subqueries first, then joins the results together: 它首先聚合子查询中的数据,然后将结果连接在一起:
select coalesce(a.productA, b.productB) as product,
coalesce(a.PriceA, 0) + coalesce(b.PriceB, 0) as price
from (select productA, sum(PriceA) as PriceA
from TableA
group by productA
) a full outer join
(select productB, sum(PriceB) as PriceB
from TableB
group by productB
) b
on a.productA = b.prodctB
I'm using a full outer join
in case the tables have different sets of products. 我正在使用full outer join
,以防表有不同的产品组。 As a result, I need to have the coalesce
in the select
statement. 因此,我需要在select
语句中使用coalesce
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.