Select back a comma delimited list grouped by an ID

前端 未结 2 1403
渐次进展
渐次进展 2020-12-03 09:42

I\'ve got the following tables:

EntryTag
---------
EntryID
TagID

Example putput (EntryID, TagID):

1 2
1 4
1 5
2 3
2 4
2 5
e         


        
2条回答
  •  抹茶落季
    2020-12-03 09:46

    DECLARE @TableOne TABLE
    (
        EntryID INT,
        TagID INT
    )
    
    DECLARE @TableTwo TABLE
    (
        TagID INT,
        Name NVARCHAR(100)
    )
    
    INSERT INTO @TableOne (EntryID,TagID)
    VALUES  (1,2)
           ,(1,4)
           ,(1,5)
           ,(2,3)
           ,(2,4)
           ,(2,1)
    
    INSERT INTO @TableTwo (TagID,Name)
    VALUES  (1,'Daniel')
           ,(2,'Samuel')
           ,(3,'Petkov')
           ,(4,'Ivan')
           ,(5,'Jack')
    
    /* 
        In this CTE we are going to format the values int the folowing way:
    
        1   2,4,5
        2   1,3,4
    
        Or for eaech EntryIDs, we will have all its TagIDs 
    
    */
    ;WITH CTE AS
    (
        SELECT DISTINCT EntryID
              ,(SELECT SUBSTRING((SELECT ',' + CAST(TagID AS NVARCHAR(10)) FROM @TableOne AS T1 WHERE T1.EntryID=T2.EntryID ORDER BY TagID FOR XML PATH('')),2,200)) AS CSVTags
        FROM @TableOne T2
    
    )
    /*
        Here we are replacing the EntryIDs with their names from the @TableTwo:
    */
    SELECT EntryID
          ,(SELECT SUBSTRING((SELECT ',' + Name FROM @TableTwo WHERE CSVTags LIKE '%'+CAST(TagID AS NVARCHAR(5))+'%' ORDER BY TagID FOR XML PATH('')),2,200) AS CSV) 
    FROM CTE
    

提交回复
热议问题