From a previous post, I have the following view in sqlite3:
CREATE View AttendeeTableView AS
SELECT (LastName || " " || FirstName) as AttendeeName,
CompanyName,
PhotoURI,
CompanyAttendeeRelation.CompanyId,
CompanyAttendeeRelation.AttendeeId
FROM Attendee
JOIN CompanyAttendeeRelation on CompanyAttendeeRelation.AttendeeId = Attendee.AttendeeId
ORDER BY LastName;
Now, since the data is generated from a many-to-many relation between Attendee
and Company
, I can get results such as:
Doe John | company A | johnPic.png | 1 | 15
Doe John | company B | johnPic.png | 2 | 15
What I'd like to do is, in cases where there's more than one company (like above), create a query that outputs:
Doe John | company A company B | johnPic.png | 1 2 | 15
And another that outputs:
Doe John | company A | company B | johnPic.png | 1 | 2 | 15
So I need to know essentially how to merge a specific column for rows that have different values in that table.
Any ideas?
Just in case, company A company B
in the first query is obviously text concatenation, That is, something along the lines of (row1.CompanyName || " " || row2.CompanyName)
The answer from this post will help you turn
into
Use the aggregate function
group_concat(X)
for that:(Using table aliases to make it shorter and easier to read.)
NULL
values are excluded from the result. The manual:The order of elements in
CompanyIds
andCompanies
is arbitrary, according to the manual:Also note that "arbitrary" is not the same as "random".
group_concat
, like other aggregate functions, processes the set of rows in the order received. Without anyORDER BY
, that order is dictated by whatever query plan is executed. There is no natural order in tables of relational databases (you cannot rely on insert order at all). But both instances ofgroup_concat()
in the sameSELECT
list process rows in the same order so that the 1st ID inCompanyIds
corresponds to the 1st name inCompanies
.You can impose your order with
ORDER BY
in a subquery. It's an implementation detail, but it's highly unlikely to change. Like:The manual about the (optional) ordinal numbers in
ORDER BY
:Use the
GROUP BY
list as leadingORDER BY
expressions for best results.Don't do anything with the derived table after ordering that might rearrange it (like joining the subquery to another table etc.)
Finally, note that similar aggregate functions in other RDBMS can behave slightly differently. Related:
I'm thinking a inner select might help, like: