加入表时得到错误的值?
getting wrong values while joining tables?
我的桌子是
Parent 我
WO PRICE
1 1790
1 9
Child 我
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 的值有误。我在 1796 年应该得到 7196。它是 parent WO 与 4 child WO 的总和。
尝试使用 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
在 之前 进行聚合 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 ;
我的桌子是
Parent 我
WO PRICE
1 1790
1 9
Child 我
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 的值有误。我在 1796 年应该得到 7196。它是 parent WO 与 4 child WO 的总和。
尝试使用 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
在 之前 进行聚合 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 ;