Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 join many-to-many, with field for each record

Author  Topic 

vfxd
Starting Member

1 Post

Posted - 2012-08-19 : 21:38:03
Hi, I have 3 tables, Table Person, Table Skill and Table JoinPersonSkill (many-to-many).

The idea is that a 'Person' can have many 'Skills'.

The JoinPersonSkill table also has a field for SkillLevel (e.g. beginner 1, novice 2, expert 3, etc).

I would like to do a select where the resulting recordset has the PersonID & Name in each record, and a *FIELD* for each skill which shows their SkillLevel.

So the result might look like this (using a generic example):

PersonID Name Basketball Soccer Volleyball
1 Adam 3 1 NULL
2 Beth 2 2 1
3 Charlie 2 NULL 2
4 Doug 1 1 1
5 Emily 3 3 3


(There is a maximum of 50 Skills so I'm not worried about creating a result with an unsupported # of fields.)

Is there a SQL statement that could join the tables & give a recordset like the table above? Can you provide an example? Thanks!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-19 : 21:46:30
yep. you could do a logic like


SELECT p.PersonID,
p.Name,
MAX(CASE WHEN s.Name = 'Basketball' THEN ps.SkillLevel END) AS Basketball,
MAX(CASE WHEN s.Name = 'Soccer' THEN ps.SkillLevel END) AS Soccer,
MAX(CASE WHEN s.Name = 'Volleyball' THEN ps.SkillLevel END) AS Volleyball
FROM Person p
INNER JOIN JoinPersonSkill ps
ON ps.PersonID = p.PersonID
INNER JOIN Skill s
ON s.SkillID = ps.SkillID
GROUP BY p.PersonID,p.Name


if you want to make skills dynamic use

http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx

also i've assumed columnnames in above statement so make sure you use actual columns instead

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -