左连接上的SQL查询问题

时间:2012-06-17 10:07:49

标签: sql-server join

我有两张桌子,我需要显示additionalcolors只有1个topatattern的玩具。实施例(FW18,FK97,FK38,LX74)。我使用了从ToytypesToyadditionalcolor的左外连接,并执行了一个子查询来查找只有toyname的toypattern。但我仍然无法得到如下结果查询的结果。

请告诉我我需要修改哪部分代码才能获得与下面的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)

1 个答案:

答案 0 :(得分:0)

嗯,我宁愿首先将ToyAdditionalColor标准化为:ToyPattern,ToyName,Color,SortOrder。

示例数据为:'FK38','Elephant','pink',1。

第二排:'FK38','大象','橙色',2。

之后,你可以使用PIVOT - 我目前还没有管理工作室,但我认为它可能是这样的:

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