我正在開發一個迷你項目來學習一些SQL。我目前在將多行組合成列時遇到了一些困難。Oracle - 通過左連接將多個行組合到列
我試圖清理表是
GroupID Product Attribute1 Attribute 2 100 1 blue red 100 2 gold blue 101 1 pink blue 101 2 black white 101 3 purple grey
我試圖生產是唯一獨特的組ID的一個表,所以:
Group ID Product1 pr1Attribute 1 pr1Attribute2 Product2 pr2Attribute1 pr2Attribute2 Product3 pr3Attribute1 pr3Attribute2
行數據:
100 1 blue red 2 gold blue null null null 101 1 pink blue 2 black white 3 purple grey
我試過以下
select distinct full.groupid, product1.product as product1,
product1.attr1 as product1_attrib1, product1.attr2 as product1_attrib2,
product2.product as product2, product2.attr1 product2_attribute1,
product2.attr2 product2_attribute2, product3.product as product3,
product3.attr1 as product3_attrib1, product3.attr2 as product1_attrib2
from tabletest full
left join tabletest product1 on (full.groupid = product1.groupid and product1.producttem = '1')
left join tabletest product2 on (full.groupid = product1.groupid and product2.producttem = '2')
left join tabletest product3 on (full.groupid = product1.groupid and product3.producttem = '3');
查詢無法正常工作。它似乎沒有考慮到AND
或以某種方式重複。
任何指導將不勝感激。我還想知道是否有一種實現這種方式的方式,以至於我不知道任何產品編號(因此基本上我不需要對它們進行硬編碼)。
您要搜索的詞是:PIVOT。有比三重自聯接更有效的方法。 –