连接表时获取错误的值?

时间:2018-03-16 15:58:59

标签: sql sql-server-2008-r2

我的桌子是

家长WO

WO     PRICE
1      1790    
1      9    

儿童WO

WO     PRICE
1      200    
1      400    
1      600
1      100

我正在尝试这样做

Select  sum(p.price), SUM(c.price) from Parent_WO p
left outer join Child_WO c
on p.WO= c.WO  
group by p.WO

我得到了p.price的错误值。我到7196时应该到1796年。它是父母WO与4孩子WO的总数的多重。

2 个答案:

答案 0 :(得分:1)

尝试使用2 CTE's;在一个CTE中计算Parent价格,在另一个CTE中计算Child价格并加入结果:

with parent_sum as (
  select
    wo
    ,SUM(price) as ParentSUM
  from parent_wo
  group by wo
)
,child_sum as (
  select
    wo
    ,SUM(price) as ChildSUM
  from child_wo
  group by wo
)
select
  p.wo
  ,ParentSUM
  ,ChildSUM
from parent_sum p
left join child_sum c
  on p.wo = c.wo

答案 1 :(得分:0)

在执行sum()之前进行聚合

Select coalesce(p.wo, c.wo) as wo, sum(p.price), SUM(c.price)
from (select p.wo, sum(p.price) as parent_price
      from Parent_WO p
      group by p.wo
     ) p full outer join
     (select c.wo, sum(c.price) as child_price
      from Child_WO c
      group by c.wo
     ) c
     on p.WO = c.WO ;