2

I'm new here and I wanted to get some help solving an Access SQL data merging problem.

Actually I would like to turn this

Customer    Comment 
James        Good
James        Bad
James        Good
James        Ugly

into this :

Customer    Comments
James       Good, Bad, Good, Ugly

I need To concatenate all the comments of the same customer into one field without VBA because I'm executing the query with PHP

Thanks

4

2 回答 2

2

Well... I know how to get the Comments concatenated properly, but I'm not sure how to pull the customer. I'm also not sure if this will work in Access, because Access doesn't support stored procs.

DECLARE @Comments VARCHAR(8000)  
SELECT @Comments = COALESCE(@Comments + ', ', '') + Comments FROM Customers

I'm guessing you'll have to do this for more than one customer, but all I can think to do is use a CURSOR for each customer, but I don't know if Access supports cursors at the moment.

DECLARE @Comments VARCHAR(8000)  
SELECT @Comments = COALESCE(@Comments + ', ', '') + Comments 
FROM Customers
WHERE Customer = @Customer (i.e. James, from the cursor)

Honestly, I think you're stuck doing this in PHP.

SELECT * FROM CUSTOMERS ORDER BY Customer, Comment

Then simply loop through the recordset and when the Customer changes, reset the Comments variable for the next customer.

于 2012-07-08T16:55:44.743 回答
0

The best way to do this is to load all the matching rows from the database and concatenate them in PHP.

You can get Access to do this, though inefficiently, using a custom function:

Public Function CommentsForCustomer(Customer As String)
   Dim sql As String
   sql = "select [Comment] from Comments where Customer = '" & Customer & "'"

   Dim rs As New ADODB.Recordset
   rs.Open sql, CurrentProject.Connection, adOpenSnapshot

   Dim text As String
   text = ""
   Do Until rs.EOF
       If Len(text) > 0 Then
           text = text & ", "
       End If
       text = text & rs.Fields("Comment")
       rs.MoveNext
   Loop
   rs.Close

   CommentsForCustomer = text
End Function

Then include the expression CommentsForCustomer([Customer]) in your query.

于 2012-07-08T17:52:35.643 回答