?
Solved

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

Posted on 2010-08-24
16
Medium Priority
?
408 Views
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.
0
Comment
Question by:ssmith94015
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 3
  • +1
16 Comments
 
LVL 9

Expert Comment

by:rg20
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
0
 

Author Comment

by:ssmith94015
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.
0
 
LVL 9

Expert Comment

by:rg20
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.
0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 

Author Comment

by:ssmith94015
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.
0
 
LVL 58

Accepted Solution

by:
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

http://www.experts-exchange.com/Microsoft/Development/MS_Access/A_2380-Domain-Aggregate-for-Concatenating-Values-by-Group-in-Microsoft-Access.html

Regards

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 "
        Else
            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, "")
            Next
            
            ' Trim leading delimiter
            
            ThisItem = Mid(ThisItem, Len(Delimiter2) + 1)
            
            ' Concatenate row result to function return value
            
            DConcatSC = Nz(DConcatSC, "") & Delimiter1 & ThisItem
            .MoveNext
        Loop
        .Close
    End With
    
    ' Trim leading delimiter
    
    If Not IsNull(DConcatSC) Then DConcatSC = Mid(DConcatSC, Len(Delimiter1) + 1)
    
    GoTo Cleanup

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

Open in new window

0
 

Author Comment

by:ssmith94015
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.
0
 
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 :)
0
 
LVL 9

Expert Comment

by:rg20
ID: 33517001
Lets try this

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

dim myarray
dim myroles
myarray=rstemp.GetRows

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
   next

0
 

Author Comment

by:ssmith94015
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!
0
 
LVL 9

Expert Comment

by:rg20
ID: 33523621
I wish everyone luck
0
 

Author Comment

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

Author Comment

by:ssmith94015
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.
0
 
LVL 93

Expert Comment

by:Patrick Matthews
ID: 33544845
Sounds fine to me.  Glad to help :)
0
 
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.
0
 

Author Comment

by:ssmith94015
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!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
Code that checks the QuickBooks schema table for non-updateable fields and then disables those controls on a form so users don't try to update them.
In Microsoft Access, when working with VBA, learn some techniques for writing readable and easily maintained code.
With Microsoft Access, learn how to start a database in different ways and produce different start-up actions allowing you to use a single database to perform multiple tasks. Specify a start-up form through options: Specify an Autoexec macro: Us…
Suggested Courses

762 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