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 |
|
MrRay
Starting Member
28 Posts |
Posted - 2006-02-27 : 18:43:15
|
| I've built a sample database of family members and their anniversaries. The member information is stored in Members, the anniversary (and a description) is stored in Couples, and the members that make up each couple are stored in CoupleMembers.I would like to have a Select statement (or stored proc) return a set of records containing each family member (Members.ID, .name, etc), their wedding date (Couples.WedDate), as well as their spouse (Members.ID, name, etc).My guess is that I would have to look for any MemberID(2) in CoupleMembers where the CoupleID for MemberID(1) is the same, but where MemberID(2) <> MemberID(1).Can somebody give me some tips on which approach makes the most sense?I know there are easier ways to set up these tables, but I also know there should be a way to accomplish this with the tables as-is.TABLE: MembersID Name1 Albert Englebert2 Jonathan Smith3 Eleanor Englebert4 Ruth Lincoln-SmithTABLE: CouplesID WEDDATE DESCRIPTION10 2001/05/23 Al & Eleanor across the street11 2003/04/12 John & Ruth from the country clubTABLE: CoupleMembersCoupleID MemberID10 110 311 211 4 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2006-02-27 : 20:03:34
|
the idea is basically just use table alias and inner join back itselfselect m.ID as Member_ID, m.Name as Member_Name, cms.MemberID as Spouce_ID, s.Name as Spouce_Name, cmo.CoupleID, c.WEDDATE, c.DESCRIPTIONfrom #Members m inner join #CoupleMembers cmo on m.ID = cmo.MemberID inner join #CoupleMembers cms on cmo.CoupleID = cms.CoupleID and cmo.MemberID <> cms.MemberID inner join #Members s on cms.MemberID = s.ID inner join #Couples c on cmo.CoupleID = c.ID ----------------------------------'KH' |
 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2006-02-27 : 20:15:09
|
| This is on the assumption that all Members is part of a Couple (record in Members will have a record in CoupleMembers). If not, use LEFT JOINMembers LEFT JOIN CoupleMembers----------------------------------'KH' |
 |
|
|
MrRay
Starting Member
28 Posts |
Posted - 2006-02-27 : 22:18:03
|
Wonderful! Thanks for opening my eyes. This has been very helpful. And yes, not all members belong to a couple (unmarried children, etc.), so LEFT JOIN will be necessary.Thanks again!quote: Originally posted by khtan This is on the assumption that all Members is part of a Couple (record in Members will have a record in CoupleMembers). If not, use LEFT JOINMembers LEFT JOIN CoupleMembers----------------------------------'KH'
|
 |
|
|
|
|
|
|
|