Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Concatenating row values on primary key

I have a requirement to concatenate values in different rows of my query based on Item ID.

For instance, I have the following rows of data.

GroupID LABEL   VALUE   UNIT
    1   Name    Henry   
    1   Guest   Manny   Guest
    1   Room    12  
    1   Milk    10      Quart
    1   Eggs    3       dozen
    2   Name    Mark    Supervisor
    2   Water   13      Litre
    2   Milk    3       Gallons
    2   Soap    12      bars

And as output, I want to get the following

ItemID     VALUE 

1          Name: Henry; Guest:Manny Guest; Room:12; Milk:10 Quart; Eggs: 3 dozen;

2          Name: Mark supervisor; Water: 13 litre; Milk: 3 Gallons; Soap: 12 bars;

How do I accomplish this please?

like image 580
Kobojunkie Avatar asked Dec 16 '22 18:12

Kobojunkie


2 Answers

You can write a recursive query based on this example (SQL Fiddle) -It now includes code to deal with NULL values in the UNIT column.

 WITH PRE 
     AS (SELECT *, 
                Row_number() 
                  OVER ( 
                    PARTITION BY GROUPID 
                    ORDER BY GROUPID) RN 
         FROM   TABLE1), 
     RECURSIVE 
     AS (SELECT *, 
                Cast(LABEL + ':' + VALUE + ' ' + Isnull(UNIT, '') + ';' AS 
                     VARCHAR( 
                     MAX)) 
                    AS FINAL 
         FROM   PRE 
         WHERE  RN = 1 
         UNION ALL 
         SELECT t1.*, 
                FINAL 
                + Cast(t1.LABEL +':' + t1.VALUE +' '+ Isnull(t1.UNIT, '') + ';' 
                AS 
                VARCHAR(MAX)) 
         FROM   PRE T1 
                INNER JOIN RECURSIVE T2 
                        ON T1.GROUPID = T2.GROUPID 
                           AND T1.RN = T2.RN + 1) 
SELECT T1.GROUPID, 
       T1.FINAL 
FROM   RECURSIVE T1 
       INNER JOIN (SELECT Max(RN) RN, 
                          GROUPID 
                   FROM   RECURSIVE 
                   GROUP  BY GROUPID) T2 
               ON T1.GROUPID = T2.GROUPID 
                  AND t1.RN = T2.RN  
like image 109
Gidil Avatar answered Jan 01 '23 18:01

Gidil


Please try:

SELECT DISTINCT a.GroupID AS ItemID,(
SELECT ISNULL(b.LABEL,'')+': '+ISNULL(b.VALUE,'')+' '+ISNULL(b.UNIT,'')+';' FROM TABLE b WHERE b.GroupID=a.GroupID
FOR XML PATH('')) AS [VALUE]
FROM TABLE a
like image 39
TechDo Avatar answered Jan 01 '23 18:01

TechDo