6

我对 SQL 查询有疑问。
我有表A:

productA priceA  
P1        18  
P2        35  
P1        22  
P2        19  

还有表B:

productB priceB  
P1        3  
P2        15  
P1        80  
P2        96  

我想要两个表中两个产品的总和。

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

请帮我。

4

3 回答 3

3

您可以使用 aunion来合并表,并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
于 2012-12-01T09:15:50.663 回答
1

这实际上是总和的总和:

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
于 2012-12-01T09:20:01.033 回答
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如果表格有不同的产品集,我正在使用。因此,我需要coalesceselect声明中包含。

于 2012-12-01T17:48:51.170 回答