Re: [SQL ] oracle 同一欄位重複只列出一筆
※ 引述《jimbosanho (chacha)》之銘言:
: 小弟最近開始接觸SQL
: 是在公司使用oracle 8i的資料庫
: 想問如果有比父子資料是像以下這樣
: 父 子
: ________ _________
: A 1
: A 2
: B 1
: B 2
: B 3
: 但是我要印出的資料只要有一筆父的資料
: 父 子
: ________ _________
: A 1
: 2
: B 1
: 2
: 3
: 重複的值選擇不列印
: 但是父子是在同一個欄位
: 意及
: 人
: ____________
: A
: 1
: 2
: B
: 1
: 2
: 3
: 第一次發問,請多包含
終於解出來,放上來讓大家看看吧!
select segment1,
description
from(
select msib.segment1,
msib.description,
msib.inventory_item_id
from bom_bill_of_materials bbom,
mtl_system_items_b msib
where bbom.assembly_item_id = msib.inventory_item_id
and exists ( select 1
from bom_inventory_components bic
where bic.bill_sequence_id = bbom.bill_sequence_id)
union all
select ' ' ||msib.segment1,
msib.description,
msib.inventory_item_id
from bom_inventory_component bic,
mtl_system_items_b msib
where bic.component_item_id = msib.inventory_item_id
and exist (select 1
from bom_bill_of_materials bbom
where bic.bill_sequence_id = bbom.bill_sequence_id)
)
order by inventory_item_id,segment1 desc
註解: union以上的部分為串出有Component(子)的Assembly(父),以下相反
用union all的原因是,不同的Assembly可能會有同一個component,只是
bill_sequence_id不一樣,為了不要讓重複的components被化成一筆
另外最後先以inventory_item_id排序,讓父子排序在一起,再作segment1
的排序是要讓父親排在兒子之前
後記:另外應該可以用connect by 跟start with來作,可是我不會,也希望能有人提供
使用方法,學SQL的第三個禮拜,路還很漫長...
bbom = bom表,儲存assembly的資訊
msib = item的項目資訊
bic = component的資訊
msib --< bbom --< bic --< msib
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 210.242.142.10
討論串 (同標題文章)