[Last Call] Learn how to a build a cloud-first strategyRegister Now


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

Posted on 2010-08-24
Medium Priority
Last Modified: 2013-11-27
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.
Question by:ssmith94015
  • 7
  • 4
  • 3
  • +1

Expert Comment

ID: 33516516
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

Author Comment

ID: 33516523
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.

Expert Comment

ID: 33516590
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 does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.


Author Comment

ID: 33516635
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.
LVL 58

Accepted Solution

cyberkiwi earned 2000 total points
ID: 33516685
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


Author Comment

ID: 33516763
Wow!  OK, time to go home so will have to get back to this tomorrow, but am looking forward to reviewing all this.
LVL 93

Expert Comment

by:Patrick Matthews
ID: 33516835
And if you need the full-throated version of the function available in that article, just give a shout :)

Expert Comment

ID: 33517001
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


Author Comment

ID: 33523604
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!

Expert Comment

ID: 33523621
I wish everyone luck

Author Comment

ID: 33526665
rf20, I hope to see you answer many of my questions to get those points!

Author Comment

ID: 33544438
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.
LVL 93

Expert Comment

by:Patrick Matthews
ID: 33544845
Sounds fine to me.  Glad to help :)
LVL 93

Expert Comment

by:Patrick Matthews
ID: 33544883
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.

Author Comment

ID: 33545953
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!

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Access is a place to store data within tables and represent this stored data using multiple database objects such as in form of macros, forms, reports, etc. After a MS Access database is created there is need to improve the performance and…
If you need a simple but flexible process for maintaining an audit trail of who created, edited, or deleted data from a table, or multiple tables, and you can do all of your work from within a form, this simple Audit Log will work for you.
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question