I admit to being an absolute SQL Noob here (I can do inner joins but that's about as "complicated" as my knowledge goes with SQL), but I am hoping for some help/insight/ideas on how to best achieve something. I have a table of companies, and a subtable of individuals for those companies. The company can have a mailing address, but it is possible that an individual would have a different mailing address to override the normal company address. I have SQL server 2008 in my environment. My thought was to have the SQL query loop through twice in the following manner
SELECT tblIndividuals.FirstName,
tblIndividuals.LastName,
tblIndividuals.CompanyName,
tblIndividuals.MailingAddress1,
tblIndividuals.MailingAddress2,
tblIndividuals.MailingAddress3,
tblIndividuals.MailingAddress4,
tblIndividuals.City,
tblIndividuals.[State],
tblIndividuals.Zip
FROM tblIndividuals
INNER JOIN tblCompanies ON tblIndividuals.CompanyName = tblCompanies.CompanyName
WHERE tblIndividuals.ChristmasList=1
AND tblIndividuals.MailingAddress1 IS NOT NULL
SELECT tblIndividuals.FirstName,
tblIndividuals.LastName,
tblIndividuals.CompanyName,
tblCompanies.MailingAddress1,
tblCompanies.MailingAddress2,
tblCompanies.MailingAddress3,
tblCompanies.MailingAddress4,
tblCompanies.City,
tblCompanies.[State],
tblCompanies.Zip
FROM tblIndividuals
INNER JOIN tblCompanies ON tblIndividuals.CompanyName = tblCompanies.CompanyName WHERE tblIndividuals.ChristmasList=1
AND tblIndividuals.MailingAddress1 IS NULL
ORDER BY tblIndividuals.CompanyName
The thought was that this way the code would loop through once, grabbing all of the individuals on the Christmas List that have a mailing address that overrides the company address, then loop through grabbing all of the individuals on the Christmas List that use the default company address, finally sorting all of the results by company name. Those of you much more well versed in SQL than I am know that this doesn't work as I hoped, instead just running two queries. Would any one much more well versed in SQL be willing to lend some insight here in a better way to achieve my ultimate goal? Any help would be greatly appreciated. Thank you for your time in advance.
edit: I know the first query doesn't really need the inner join, I just had copied/pasted from the second query and didn't change it. >.<