user1348424
user1348424

Reputation: 839

Combine multiple rows into single row in an CSV file in SSIS

I load data from SQL to CSV file. And my csv records are in the following way.

Eid  ename  desig  sourceD  location  
1     Ralf   PM      1        UK  
1     Ralf   PM      1        USA  
2     Marty  PL      3         GBR  
3     Levis  BA      5        UK  
4     Ricky  BI      7        RSA  
4     Ricky  BI      7        FRA 

now i want to combine EID 1 and 4 into single rows. My output has to be in the following way

Eid  ename  desig  sourceD  location  
1     Ralf   PM      1        UK, USA  
2     Marty  PL      3         GBR  
3     Levis  BA      5        UK  
4     Ricky  BI      7        RSA, FRA   

I have only CSV File i dont have any sql Query or anything.

Upvotes: 1

Views: 1054

Answers (1)

Justin
Justin

Reputation: 9724

SQL Fiddle

SQL Query

    select c1.Eid, c1.ename,c1.desig,c1.sourceD,
    (   SELECT x.location + ', '
        FROM Contacts x
        WHERE c1.Eid = x.Eid
        ORDER BY x.location
        FOR XML PATH ('')
    ) as Locations
from Contacts c1
group by c1.Eid, c1.ename,c1.desig,c1.sourceD

Working ?

If you want without comma in the end:

    SELECT c1.Eid, c1.ename,c1.desig,c1.sourceD,
   LEFT( (   SELECT x.location + ', '
        FROM Contacts x
        WHERE c1.Eid = x.Eid
        ORDER BY x.location
        FOR XML PATH ('')
    ),LEN((   SELECT x.location + ', '
        FROM Contacts x
        WHERE c1.Eid = x.Eid
        ORDER BY x.location
        FOR XML PATH ('')
    ))-1) AS Locations
FROM Contacts c1
GROUP BY c1.Eid, c1.ename,c1.desig,c1.sourceD

This Query will let you avoid lenght 0:

    SELECT c1.Eid, c1.ename,c1.desig,c1.sourceD,
   LEFT( (   SELECT x.location + ', '
        FROM Contacts x
        WHERE c1.Eid = x.Eid
        ORDER BY x.location
        FOR XML PATH ('')
    ),CASE WHEN LEN((   SELECT x.location + ', '
        FROM Contacts x
        WHERE c1.Eid = x.Eid
        ORDER BY x.location
        FOR XML PATH ('')
    ))=0 THEN 1 ELSE LEN((   SELECT x.location + ', '
        FROM Contacts x
        WHERE c1.Eid = x.Eid
        ORDER BY x.location
        FOR XML PATH ('')
    )) END -1) AS Locations
FROM Contacts c1
GROUP BY c1.Eid, c1.ename,c1.desig,c1.sourceD

Upvotes: 2

Related Questions