I have three tables. Leads, Notes and Users.
leads
- id
- name
notes
- id
- lead_id
- content
- user_id
users
- id
- name
I would like to construct a query to return new table with two columns
Lead name | Notes
John | Mary - Note 1 ### John - Note 2
First column is straightforward. Every lead has a name. Second column however is a tricky one. I want to aggregate all notes to single column with addition to prepending note's author's name.
I wrote a query with second column that has aggregated notes.
SELECT leads.name AS name,
string_agg(notes.content, ' ### ') AS leads_notes,
FROM leads
INNER JOIN notes ON notes.lead_id = leads.id
GROUP BY leads.id
But note's author name (users.name
) I do not how to query.