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.
| Author |
Topic |
|
jonahpup
Starting Member
4 Posts |
Posted - 2010-09-23 : 16:46:55
|
Hi... Here is a basic rundown on my tables and how they are setup Dog TableId int, Not Null, Primary KeyDogName nvarchar(50)Person TableId int, Not Null, Primary KeyFirstName nvarchar(50)LastName nvarchar(50)DogPersonMap TableDogId int, Not Null, Primary KeyPersonId int, Not Null, Primary KeyEvent TableId int, Not Null, Primary KeyName nvarchar(50)DogEventMap TableDogId int, Not Null, Primary KeyEventId int, Not Null, Primary KeyWhat to be able to get the following results:Dog - Owners - EventsAbbey - Chris, Suzan, Bob - Jumping, Swimming, EatingKing - Chris, Robbie - Jumping, Swimming, EatingRufus - Suzan, Robbie - Swimming, Eating, Sleepingbut I have absolutely no idea how to do this in sql, I am using sqlserver 2008.can anyone help me?? PLEASE!!CheersChris |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2010-09-23 : 17:03:15
|
Try this:select d.DogName Dog, Stuff(( select ', '+P.FirstName from Person P inner join DogPersonMap M on M.PersonID=P.ID where M.DogID=D.ID FOR XML PATH('')),1,2,'') Owners,Stuff(( select ', '+E.Name from Event E inner join DogEventMap M on M.EventID=E.ID where M.DogID=D.ID FOR XML PATH('')),1,2,'') Eventsfrom Dog D |
 |
|
|
jonahpup
Starting Member
4 Posts |
Posted - 2010-09-23 : 18:00:41
|
| Thank you so much... works like a dream... that gives me a basis to work from... |
 |
|
|
jonahpup
Starting Member
4 Posts |
Posted - 2010-09-23 : 19:54:18
|
| I have added to this code to get all the data I require, however, I am getting duplicate results for some of the events... not sure why??eg: Some dogs are showing the same event twice in the 'Events' output even though they only appear once in the database... something to do with the inner join?? |
 |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2010-09-23 : 20:07:15
|
| try just addingselect distinct d.DogName Dog, etc.JimEveryday I learn something that somebody else already knew |
 |
|
|
|
|
|
|
|