Goal (assuming this schema must remain the same):
What is the most recent outreach for the first salesperson created per company?
- For each record in the company table, get the corresponding record in the company_salesperson table using a matching company_salesperson.customer_id value and the MAX(company_salesperson.created_at) value.
- {For the company record w/ id == 1: this should return company_salesperson record w/ id == 2}
- For each returned company_salesperson record, get all company_salesperson_company_outreach records with a matching company_salesperson_company_outreach.company_salesperson_id value
- For the company_salesperson record w/ id == 2, this should return two company_salesperson_company_outreach records w/ id's 2 and 3
- For each set of returned company_salesperson_company_outreach records, get the corresponding company_outreach record withe the MAX(company_outreach.outreach_id)
- For the company_salesperson_company_outreach records w/ id's 2 and 3, we should get corresponding company_outreach records w/ id's 2 and 3. Based on their company_outreach.outreach_id values, this should see that company_outreach record w/ id == 3 has a greater company_outreach.outreach_id value. Therefore this should return company_salesperson_company_outreach record w/ id == 3.
Desired Output:
SELECT company.id, company_salesperson.id, company_salesperson_company_outreach.id, company_outreach.id
FROM ...???
| company.id | company_salesperson.id | company_salesperson_company_outreach.id | company_outreach.id |
|---|---|---|---|
| 1 | 2 | 3 | 3 |
I feel that there is a very elegant solution to this, but after three days of my brain melting out of my ears, I was advised to reach out here! Thank you for your time.

