Concatenate / Concatenate in SQL
I am trying to reorder / group a result set using SQL. I have several fields (which have been renamed to something less specific for the sake of example), and each logical group of records has a field that remains constant - an address field. There are also fields that are present for each address, they are the same for each address.
id forename surname address
1 John These Address1
2 Lucy Values Address1
3 Jenny Are Address1
4 John All Address2
5 Lucy Totally Address2
6 Jenny Different Address2
7 Steve And Address2
8 Richard Blah Address2
address John Lucy Jenny Steve Richard
Address1 These Values Are (null) (null)
Address2 All Totally Different And Blah
For example: John, Lucy, Jenny, Steve and Richard are the only possible names for each address. I know this because it is stored elsewhere.
Can I select values ββfrom the actual entries in the left hand image and return them as a result set similar to the one on the right? I am using MySQL if it matters.
source to share
Assuming the column headings are "john", "lucy", etc. fixed, you can group by address field and use if () functions in combination with aggregate operators to get your results:
select max(if(forename='john',surname,null)) as john,
max(if(forename='lucy',surname,null)) as lucy,
max(if(forename='jenny',surname,null)) as jenny,
max(if(forename='steve',surname,null)) as steve,
max(if(forename='richard',surname,null)) as richard,
address
from tablename
group by address;
It's a little flimsy though.
There is also a group_concat function that can be used (within the constraints) to do something like this, but it will be ordered by row, not by column as you think.
eg.
select address, group_concat( concat( forename, surname ) ) tenants
from tablename
group by address;
source to share