Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Aggregating strings together

In my SQL Server 2005 database, using an SLQ query, does anyone know the best way to group records together by one field, and get a comma-separated list of the values from another?
So if I have:

UserID        Code
  1            A
  1            C5
  1            X
  2            V3
  3            B
  3            D
  3            NULL
  3            F4
  4            NULL

I'd get:

 UserID        Code
  1            A,C5,X
  2            V3
  3            B,D,F4
  4            NULL

Thanks for any help.

like image 393
Luke Avatar asked Mar 27 '11 21:03

Luke


People also ask

How do you aggregate strings in SQL?

The STRING_AGG() is an aggregate function that concatenates rows of strings into a single string, separated by a specified separator. It does not add the separator at the end of the result string. In this syntax: input_string is any type that can be converted VARCHAR and NVARCHAR when concatenation.

Can you sum strings in SQL?

In SQL, the SUM() function is an aggregate function that returns the sum of all values in a given expression. It can also be used to return the sum of all distinct (unique) values in an expression. The expression must be numeric (it cannot be character string, bit string, or datetime).

How do I group concatenate strings in SQL?

To concatenate strings in MySQL with GROUP BY, you need to use GROUP_CONCAT() with a SEPARATOR parameter which may be comma(') or space (' ') etc.


2 Answers

WITH Data AS (
    SELECT 1 UserId, 'A' Code 
    UNION ALL 
    SELECT 1, 'C5'
    UNION ALL 
    SELECT 1, 'X'
    UNION ALL 
    SELECT 2, 'V3'
    UNION ALL 
    SELECT 3, 'B'
    UNION ALL 
    SELECT 3, 'D'
    UNION ALL 
    SELECT 3, NULL
    UNION ALL 
    SELECT 3, 'F4'
    UNION ALL 
    SELECT 4, NULL
)
SELECT U.UserId, STUFF((
    SELECT ','+Code FROM Data WHERE Data.UserID = U.UserID FOR XML PATH('')
), 1, 1, '') Code 
FROM (SELECT DISTINCT UserID FROM Data) U

Just replace the Data CTE with your table name and you're done.

like image 195
Lucero Avatar answered Nov 15 '22 14:11

Lucero


There it´s a complete review of forms to do that in TSQL

http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

like image 25
pcofre Avatar answered Nov 15 '22 16:11

pcofre