Solved

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

Posted on 2010-08-24
16
397 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
  • 7
  • 4
  • 3
  • +1
16 Comments
 
LVL 9

Expert Comment

by:rg20
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:ssmith94015
Comment Utility
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 500 total points
Comment Utility
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
Comment Utility
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 92

Expert Comment

by:Patrick Matthews
Comment Utility
And if you need the full-throated version of the function available in that article, just give a shout :)
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 9

Expert Comment

by:rg20
Comment Utility
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
Comment Utility
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
Comment Utility
I wish everyone luck
0
 

Author Comment

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

Author Comment

by:ssmith94015
Comment Utility
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 92

Expert Comment

by:Patrick Matthews
Comment Utility
Sounds fine to me.  Glad to help :)
0
 
LVL 92

Expert Comment

by:Patrick Matthews
Comment Utility
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
Comment Utility
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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Append - add current date 5 25
Access Text File Export Results in Very Large File size 11 27
Combobox issue 4 25
Splitting out Data 14 26
In a multiple monitor setup, if you don't want to use AutoCenter to position your popup forms, you have a problem: where will they appear?  Sometimes you may have an additional problem: where the devil did they go?  If you last had a popup form open…
Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
The viewer will learn how to simulate a series of sales calls dependent on a single skill level and learn how to simulate a series of sales calls dependent on two skill levels. Simulating Independent Sales Calls: Enter .75 into cell C2 – “skill leve…
The viewer will learn how to create a normally distributed random variable in Excel, use a normal distribution to simulate the return on an investment over a period of years, Create a Monte Carlo simulation using a normal random variable, and calcul…

728 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now