• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 415
  • Last Modified:

Move multiple fields on multip rows into one field on one row

I have a database with contacts.  Each contact can have multple roles, that is, John Smith can be President, Main Contact, Senrior Manger and Business Contanct.  So, he has four roles and thus there are four rows for him.  I need to colapse this into one row and his roles into one field so that it reads: President, Main Contact, Senior Manager, Business Contact
in ONE field for him.  Any suggestions as I have 4,000 rows of people I need to do this for.
  • 7
  • 4
  • 3
  • +1
1 Solution
update users set new_field_name = Field1&","&field2&",".......

Add the new field to the table first.  The update will append all the fields into one field.

If the field is true of false, then you will need a translation step in there to append only the field names that are true
ssmith94015Author Commented:
The data is  in one field so I cannot concatenate fields, that is, there are four rows for the field that need to be collapsed into one field row.
I see, so if I understand correctly, you have one field name "Role" and there can be 4 choices.

So if Joe is an President and  Main Contact, there will be 2 records in the database for him (spreadsheet style)

I understand that you want to either add all the rows in one database field, which just changes the select statement, or you want to add additional columns to handle multiple rows

If you want to merge them into one field, you can use a select role groupby user.  This will give you all the records for that user, then a loop through the recordset will give you the update fields as they appear.

Sorry if I am off base here.
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

ssmith94015Author Commented:
Yes, that is it.  A person can have many roles and I understand the group by, but even if I group by the person, I still get four rows in the group by as each role is distinct.  These are text fields so the grouping won't work.
You can add the function in the code box in a VBA module
Usage: add this expression as a new column to your query

DConcatSC("[Role]","[TblName]","[PersonID]", [PersonID]) AS RoleList

Replace PersonID, TblName and Role with the correct column/table names.
This my simplification of a function by Patrick from



Function DConcatSC(ConcatColumns As String, Tbl As String, Optional CriteriaField As String = "", _
    Optional CriteriaValue As Variant, _
    Optional Delimiter1 As String = ", ", Optional Delimiter2 As String = ", ", _
    Optional Distinct As Boolean = True, Optional Sort As String = "Asc", _
    Optional Limit As Long = 0)
    ' Function by Patrick G. Matthews, basically embellishing an approach seen in many
    ' incarnations over the years
    ' Requires reference to Microsoft DAO library
    ' This function is intended as a "domain aggregate" that concatenates (and delimits) the
    ' various values rather than the more usual Count, Sum, Min, Max, etc.  For example:
    '    Select Field1, DConcatSC("Field2", "SomeTable", "[Field1]", Field1) AS List
    '    FROM SomeTable
    '    GROUP BY Field1
    ' will return the distinct values of Field1, along with a concatenated list of all the
    ' distinct Field2 values associated with each Field1 value.
    ' ConcatColumns is a comma-delimited list of columns to be concatenated (typically just
    '   one column, but the function accommodates multiple).  Place field names in square
    '   brackets if they do not meet the customary rules for naming DB objects
    ' Tbl is the table/query the data are pulled from.  Place table name in square brackets
    '   if they do not meet the customary rules for naming DB objects
    ' Criteria (optional) are the criteria to be applied in the grouping.  Be sure to use And
    '   or Or as needed to build the right logic, and to encase text values in single quotes
    '   and dates in #
    ' Delimiter1 (optional) is the delimiter used in the concatenation (default is ", ").
    '   Delimiter1 is applied to each row in the code query's result set
    ' Delimiter2 (optional) is the delimiter used in concatenating each column in the result
    '   set if ConcatColumns specifies more than one column (default is ", ")
    ' Distinct (optional) determines whether the distinct values are concatenated (True,
    '   default), or whether all values are concatenated (and thus may get repeated)
    ' Sort (optional) indicates whether the concatenated string is sorted, and if so, if it is
    '   Asc or Desc.  Note that if ConcatColumns has >1 column and you use Desc, only the last
    '   column gets sorted
    ' Limit (optional) places a limit on how many items are placed into the concatenated string.
    '   The Limit argument works as a TOP N qualifier in the SELECT clause
    Dim rs As DAO.Recordset
    Dim SQL As String
    Dim ThisItem As String
    Dim FieldCounter As Long
    On Error GoTo ErrHandler
    ' Initialize to Null
    DConcatSC = Null
    ' Build up a query to grab the information needed for the concatenation
    Dim realCriteriaValue As String
    If CriteriaField <> "" Then
        If IsNull(CriteriaValue) Then
            realCriteriaValue = " IS NULL "
            realCriteriaValue = "='" & Replace(CriteriaValue, "'", "''") & "' "
        End If
    End If
    SQL = "SELECT " & IIf(Distinct, "DISTINCT ", "") & _
            IIf(Limit > 0, "TOP " & Limit & " ", "") & _
            ConcatColumns & " " & _
        "FROM " & Tbl & " " & _
        IIf(CriteriaField <> "", "WHERE " & CriteriaField & realCriteriaValue, "") & _
        Switch(Sort = "Asc", "ORDER BY " & ConcatColumns & " Asc", _
            Sort = "Desc", "ORDER BY " & ConcatColumns & " Desc", True, "")
    ' Open the recordset and loop through it:
    ' 1) Concatenate each column in each row of the recordset
    ' 2) Concatenate the resulting concatenated rows in the function's return value

    Set rs = CurrentDb.OpenRecordset(SQL)
    With rs
        Do Until .EOF
            ' Initialize variable for this row
            ThisItem = ""
            ' Concatenate columns on this row
            For FieldCounter = 0 To rs.Fields.Count - 1
                ThisItem = ThisItem & Delimiter2 & Nz(rs.Fields(FieldCounter).Value, "")
            ' Trim leading delimiter
            ThisItem = Mid(ThisItem, Len(Delimiter2) + 1)
            ' Concatenate row result to function return value
            DConcatSC = Nz(DConcatSC, "") & Delimiter1 & ThisItem
    End With
    ' Trim leading delimiter
    If Not IsNull(DConcatSC) Then DConcatSC = Mid(DConcatSC, Len(Delimiter1) + 1)
    GoTo Cleanup

    ' Error is most likely an invalid database object name, or bad syntax in the Criteria
    DConcatSC = CVErr(Err.Number)
    Set rs = Nothing
End Function

Open in new window

ssmith94015Author Commented:
Wow!  OK, time to go home so will have to get back to this tomorrow, but am looking forward to reviewing all this.
Patrick MatthewsCommented:
And if you need the full-throated version of the function available in that article, just give a shout :)
Lets try this

SQL = "Select distinct(user) as name from users"
set rstemp=conntemp.execute(SQL)

dim myarray
dim myroles

for counter=0 to ubound(myarray,1)
SQL = "select roles from users where user='"&myarray(1)&"'"
set rsRoles=conntemp.execute(SQL)

myroles = rsRoles.GetRows
'Now you have all the roles for a user, use a Join function to turn them into a comma delimited string
rolestring = join(myroles,",")
'or write an update loop for each user
    for counter2 = 0 to ubound(myroles,1)
         update table with role

ssmith94015Author Commented:
Cyberkiwi and matthewspatrick, looks like that is the way I am going to go.  It will take me a bit to apply to my needs, but will let you know how it goes as the results sample is what I am looking for.  Will take a few days to get back to this question as I have just been pulled off this project to another "emergency" that will take a few days to resolve.  

rg20, thank you for the suggestion, but am going to go with the above's samples.  

Wish me luck!
I wish everyone luck
ssmith94015Author Commented:
rf20, I hope to see you answer many of my questions to get those points!
ssmith94015Author Commented:
Wrks perfectly.  Does exactly what I want so now, how do I split points as I did use matthewspatrick code straight without changes yet cyberkiwi gave the suggestion first and referenced patrick's code.  OK, 300 to cyberkiwi and 200 to patrick - hope that seems fair.
Patrick MatthewsCommented:
Sounds fine to me.  Glad to help :)
Patrick MatthewsCommented:
On second thought...There is no need to assign me points here, as long as you include cyberkiwi's comment http:#a33516691 (the one where he linked to my article) in the split.  EE has a system where if there is an article URL in an accepted or assisted answer, the article author gets bonus points.Which is awesome, because every time cyberkiwi recommends one of my articles, I stand to earn a few points :)Works kind of like royalties paid to book authors and songwriters.
ssmith94015Author Commented:
Will do as you request.  I ttried wice to assign points, but am getting an error, so will try again later.  BTW, people here were SOOOOO impressed with my (ahem!) your code - I told them I "borrowed" it from you and I have left your name in the comments crediting it to you - that now they want a version to work with the EXCEL lists.  If I have problems, will definetely post a question!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

  • 7
  • 4
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now