0

Current Table:



txtFullName  | First Activity
_____________________________

Joe Bloggs   | Football

Joe Bloggs   | Tennis    

Katie Bloggs | Tennis


Where I'm trying to get it as...

txtFullName  | First Activity
_____________________________
Joe Bloggs   | Football, Tennis

Katie Bloggs | Tennis



**I've tried using COALESCE AND FOR XML PATH('').. Which I can't seem to fit correctly in this statement.. is there another way to do the same thing?

Any help would be appreciated!!

dan6657
  • 117
  • 2
  • 11

2 Answers2

2

Here have an example with XML based on your result. Now you can put your query inside of a CTE and apply this solution to the result.

declare @tbl as table (
    txtFullName varchar(15)
    ,firstActivity varchar(15)
)

insert into @tbl values ('Joe Bloggs', 'Football')
insert into @tbl values ('Joe Bloggs', 'Tennis')
insert into @tbl values ('Katie Bloggs', 'Tennis')



SELECT
    txtFullName
    ,STUFF(
        (SELECT ', ' + firstActivity
        FROM @tbl
        WHERE txtFullName = a.txtFullName
        FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,1,'') AS firstActivity
FROM @tbl a
GROUP BY txtFullName

UPDATE:

SELECT
    t0.txtFullName AS 'Name'
    ,t1.[FirstActivity]
FROM (
    SELECT txtFullName FROM tblMembers WHERE txtForm = '10'
) T0 
LEFT JOIN (
    SELECT
        txtFullName
        ,STUFF(
        (SELECT ', ' + txtName
        FROM tblLists
        INNER JOIN tblAllLists
            ON tblLists.intID = tblAllLists.intID
        INNER JOIN tblMembers
            ON tblAllLists.instuiID = tblMembers.instuiID
        WHERE txtFullName = M.txtFullName
        FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,1,'') AS firstActivity
    FROM tblLists
    INNER JOIN tblAllLists
        ON tblLists.intID = tblAllLists.intID
    INNER JOIN tblMembers M
        ON tblAllLists.instuiID = M.instuiID 
    WHERE txtDay = 'Mon' AND txtForm = '10' AND txtDesc='Norm'
    GROUP BY txtFullName
) T1
    ON t0.txtFullName = t1.txtFullName
Valerica
  • 1,618
  • 1
  • 13
  • 20
1

You can use STRING_AGG (since SQL Server 2017)

SELECT
    txtFullName,
    STRING_AGG(txtName,',')  AS 'First Activity'
FROM
    tblLists
    INNER JOIN tblMembers ON
        tblLists.txtInstituID = tblMembers.txtInstituID
    INNER JOIN tblAllLists ON
        tblLists.intID = tblAllLists.intID 
WHERE
  Day = 'Mon' AND
  txtForm = '10' AND
  Desc='Norm' AND
  txtID = '10'
GROUP BY
    txtFullName
Indent
  • 4,675
  • 1
  • 19
  • 35
  • Doesn't quite work on 14 which i'm currently working with, thanks though need to look at upgrading. – dan6657 Oct 31 '17 at 15:49