Left Outer Join返回重复记录 - Oracle

时间:2017-12-09 02:26:46

标签: oracle duplicates left-join

场景:

将表ORDER与表COST连接 其中COST具有多行,用于表ORDER

中的单个引用

期望的结果:

每个订单返回单行及其相关费用。

ID NAME PRICE GST
1  Book 100   10
2  CD   50    5

例如:

表格订单

ID   NAME  COST
1    Book  110
2    CD    55

表COST

ID ORDER_ID COST_TYPE VALUE
1   1   PRICE      100
2   1   GST        10
3   2   PRICE      50
4   2   GST        5

LEFT OUTER JOIN在使用以下条件时返回多行

SELECT * from ORDER
LEFT OUTER JOIN COST
ON ORDER.ID = COST.ORDER_ID

3 个答案:

答案 0 :(得分:2)

select o.id, o.name, c.price, c.gst
from   order o left outer join
       ( select   order_id, 
                  sum(case when cost_type = 'PRICE' then value end) as price,
                  sum(case when cost_type = 'GST'   then value end) as gst
         from     cost
         group by order_id
       ) c
       on o.id = c.order_id
;

答案 1 :(得分:0)

所以Select ORDER.ID, COST.COST_TYPE, COST.VALUE from ORDERS LEFT OUTER JOIN COST ON ORDER.ID = COST.ORDER_ID and COST.COST_TYPE = 'PRICE'

如果您没有指定COST_TYPE,那么它会返回多行,因为ORDER_ID会在您的COST TABLE上重复。

答案 2 :(得分:0)

这就是我在我的案例中找到的工作。

必须使用2 LEFT OUTER JOIN&alias才能让它正常工作

SELECT ID, NAME, PRICE.value as PRICE, GST.value as GST 
from ORDER

LEFT OUTER JOIN COST as PRICE
ON ORDER.ID = COST.ORDER_ID
AND PRICE.COST_TYPE = 'PRICE'

LEFT OUTER JOIN COST as GST
ON ORDER.ID = COST.ORDER_ID
AND GST.COST_TYPE = 'GST'