I have a table of 'members' which looks like the following. In trying to put together a mailing list I found the addresses were easy. The names on the other hand, not so much.
| id | firstName | lastName | mbrGrpNum | mbrGrpNumID | dateJoined |
--------------------------------------------------------------------
| 1 | Jane | Whitmore | 100100 | 01 | 2016-01-01 |
| 2 | Bob | Whitmore | 100100 | 02 | 2014-02-01 |
| 3 | Carol | Evans | 100101 | 01 | 2012-02-01 |
| 4 | Bob | Roahns | 100101 | 02 | 2015-09-28 |
| 5 | Corry | Roahns | 100101 | 03 | 2014-09-28 |
The output I'd like to get is something like this, based on the mbrGrpNum;
1 Whitmore, Jane (01/16) & Bob (02/14)
2 Evans, Carol (02/12) & Rohns, Bob (09/15) & Corry (09/14)
There could be up to six individuals with the same mbrGrpNum
(essentially the members of a household) all with different mbrGrpNumID
's.
Use CONCAT
to concatenate columns in a row, and GROUP_CONCAT
to concatenate all those in a group.
SELECT GROUP_CONCAT(
CONCAT(lastName, ', ', firstName, ' (',
DATE_FORMAT(dateJoined, '%m/%y'), ')')
SEPARATOR ' & ') AS members
FROM members
GROUP BY mbrGrpNum
To combine members with the same last name, you need to use a subquery to find them.
SELECT GROUP_CONCAT(CONCAT(lastName, ', ', family_members) SEPARATOR ' & ') AS members
FROM (
SELECT mbrGrpNum, lastName,
GROUP_CONCAT(
CONCAT(firstName, ' (', DATE_FORMAT(dateJoined, '%m/%y'), ')') SEPARATOR ' & ') AS family_members
FROM members
GROUP BY mbrGrpNum, lastName) AS families
GROUP BY mbrGrpNum
@barmar Is it possible to join the entire contents of a table (i.e. 'addresses') the "combined members" concat (second one listed above) to get the output of the concatenation with the address info?