2012-12-01 68 views
6

我有SQL查询的问题。
我有表A:总计不同表中的总和

productA priceA 
P1  18 
P2  35 
P1  22 
P2  19 

也tableB的:

productB priceB 
P1  3 
P2  15 
P1  80 
P2  96 

我想作为导致两款产品从2代表的总和。

product price 
P1  123 
P2  165 

我想总结两个表的总和。
我正在尝试此查询,但它是错误的。

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 

请帮帮我。

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 
+0

你能解释一下你的意思吗?“这是错误的” - 查询产生了什么? 2个子选择是否为每个单独的产品返回正确的结果? –

+0

你的引擎是什么? – Sebas

回答

3

你可以使用一个union合并表,group by

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 
+0

它的工作原理!谢谢! :) – vaka

+0

因为你有'union all',所以我很高兴你。 –

1

这是毫不夸张地金额的总和:对结果

+1

此解决方案不正确,因为'union'删除了重复项。你应该有'union all'。 –

+0

@GordonLinoff该死的,你是对的!我通常是“全体工会”的纳粹。感谢您指出了这一点。 (我修正了查询) – Bohemian

0

因为加入似乎是一个自然方法来解决这个问题,这里是与join而不是union解决方案。它集合了数据在第一子查询,然后将结果连接在一起:

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 

我使用的是full outer join的情况下,表中有不同的产品。因此,我需要在select声明中有​​3210。