2012-06-17 160 views
1

我有兩個表,我需要顯示additionalcolors玩具,只有1 toypattern。例子(FW18,FK97,FK38,LX74)。我使用了從ToytypesToyadditionalcolor的左外連接,並且還執行了子查詢來查找只有玩具名稱的toypattern。但是我仍然無法像下面的結果查詢那樣得到結果。左連接SQL查詢問題

請告訴我我需要修改哪部分代碼才能獲得與下面query1表類似的結果?

ToyTypes

ToyPattern ToyName   mainColor 
---------- --------------- --------- 
    F692   Dino    pink  
    F692   Elephant   pink   
    FK38   Elephant   pink   
    FK97   Giraffe   purple  
    FW18   Sonic   pink  
    LX73   Kangaroo   pink  
    LX73   Cow    blush  
    LX73   Dog    pink  
    LX74   Cat    plum   

ToyAdditionalColor

ToyPattern ToyName  firstColor additionalColor 
---------- ---------- ----------- ---------------- 
    FK38  Elephant pink   orange 
    FK38  Elephant pink   yellow 
    LX74  cat   plum   dark pink 
    LX74  cat   plum   pale pink 

所需的輸出:

ToyPattern ToyName  color 1  color 2  color 3  color 4  color 5  
----------- ---------- ------------ ------------ ------------ ------------ ------------ 
FK38  Elephant pink   orange  yellow  NULL   NULL  
FK97  Giraffe  purple  NULL   NULL   NULL   NULL 
FW18  Sonic  pink   NULL   NULL   NULL   NULL 
LX74  cat   plum   dark pink pale pink NULL   NULL 

下面,這裏是我的SQL代碼。

select distinct 
    toytypes.toypattern, 
    toyname, 
    toytypes.flowerBreed, 
    toytypes.firstColor as 'color 1' 
from 
    Toytypes 
left join 
    ToyAdditionalColor on ToyAdditionalColor.toypattern = Toytypes.toypattern 
where 
    toytypes.toypattern in 
       (select Toypattern 
       from Toytypes 
       group by toypattern 
       having count(toypattern) < 2) 

回答

0

嗯我寧願通過標準化ToyAdditionalColor成爲像開始:ToyPattern,ToyName,顏色,SortOrder的。

實施例的數據會是: 'FK38', '象', '粉紅',1

第二行: 'FK38', '象', '桔子',2

之後,你可以使用PIVOT - 我還沒有在此刻得到了Management Studio中有我,但我認爲這可能是這樣的:

SELECT 
    ToyPattern 
    , ToyName 
    , 'color 1' = 1 
    , 'color 2' = 2 
    , 'color 3' = 3 
    , 'color 4' = 4 
    , 'color 5' = 5 
FROM ( 
    SELECT 
    ToyPattern 
    , ToyName 
    , SortOrder 
    , Color 
    FROM 
    dbo.ToyAdditionalColor 
) AS ToyAdditionalColor PIVOT (
    MAX (Color) FOR SortOrder IN (1,2,3,4,5) 
) AS PivotTable 
+0

嗨YS,現在的問題是我們沒有假設進行規範化。是的,這些表格沒有被標準化,我們被要求使用上面的表格來執行查詢,並得到與desir相同的結果編輯輸出。 – setiasetia

+0

但我不應該正常化這個問題的表...... – setiasetia

+0

謝謝你的提示。我想我已經得到了這個概念。謝謝! – setiasetia