开发者

SQL Joining on a one-to-many relationship

开发者 https://www.devze.com 2022-12-22 23:28 出处:网络
Ok, here was my original question; Table one contains ID|Name 1Mary 2John Table two contains ID|Color 1Red 1Blue

Ok, here was my original question;

Table one contains

ID|Name  
1  Mary  
2  John  

Table two contains

ID|Color  
1  Red  
1  Blue
2  Blue  
2  Green  
2  Black  

I want to e开发者_如何学编程nd up with is

ID|Name|Red|Blue|Green|Black  
1  Mary Y   Y  
2  John     Y     Y     Y

It seems that because there are 11 unique values for color and 1000's upon 1000's of records in table one that there is no 'good' way to do this. So, two other questions.

Is there an efficient way to query to get this result? I can then create a crosstab in my application to get the desired result.

ID|Name|Color  
1  Mary  Red  
1  Mary  Blue  
2  John  Blue  
2  John  Green  
2  John  Black

If I wanted to limit the number of records returned how could I do a query to do something like this?

Where ((color='blue') AND (color<>'red' OR color<>'green'))

So using the above example I would then get back

ID|Name|Color  
1  Mary  Blue  
2  John  Blue  
2  John  Black

I connect to Visual FoxPro tables via ADODB to use SQL. Thanks!


From your prior question, and querying against a VFP table, you could get your results by the following VFP qualified query... cross-tab complete

select
      N.ID,
      N.Name,
      MAX( IIF( C.Color = "Red", "Y", " " )) Red,
      MAX( IIF( C.Color = "Blue", "Y", " " )) Blue,
      MAX( IIF( C.Color = "Green", "Y", " " )) Green,
      MAX( IIF( C.Color = "Black", "Y", " " )) Black
   FROM
      C_Names N,
      Colors C
   WHERE
      N.ID = C.ID
   GROUP BY 
      N.ID,
      N.Name

Then, as you have other "colors", just copy the MAX( IIF()) for that respective color and have the column as the result column name... follow the pattern. Only issue is if you have different case-sensitve spelling of the colors, then you may need to UPPER( C.Color ) = "RED" (or similar for other colors)


You are looking to make a crosstab query. You could try to use the crosstab query wizard:
http://msdn.microsoft.com/en-us/library/aa979431%28VS.71%29.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号