I’m trying to reorder/group a set of results using SQL. I have a few fields (which for the example have been renamed to something a bit less specific), and each logical group of records has a field which remains constant – the address field. There are also fields which are present for each address, these are the same for every 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 at each address. I know this because it’s stored in another location.
Can I select values from the actual records in the left hand image, and return them as a result set like the one on the right? I’m using MySQL if that makes a difference.
Assuming that the column headings ‘john’, ‘lucy’ etc are fixed, you can group by the address field and use if() functions combined with aggregate operators to get your results:
It is a bit brittle though.
There is also the group_concat function that can be used (within limits) to do something similar, but it will be ordered row-wise rather than column-wise as you appear to require.
eg.