How to concatenate strings from multiple rows in one column + inner join in one query

后端 未结 4 1107
南旧
南旧 2021-01-02 09:16

I have a query with the following result: query:

SELECT Tasks.TaskId, Comments.Comment, comments.timespent       
FROM   comments
INNER JOIN tasks ON commen         


        
4条回答
  •  长发绾君心
    2021-01-02 09:59

    Ok, this is a bit more complicated but it doesn't use xml, and it can be used with other databases than sql server:

        WITH orig
             AS (SELECT 1 AS f1, 'C11' AS f2
                 UNION ALL
                 SELECT 1 AS f1, 'C12' AS f2
                 UNION ALL
                 SELECT 1 AS f1, 'C13' AS f2
                 UNION ALL
                 SELECT 2 AS f1, 'C21' AS f2
                 UNION ALL
                 SELECT 2 AS f1, 'C22' AS f2
                 UNION ALL
                 SELECT 2 AS f1, 'C23' AS f2
                 UNION ALL
                 SELECT 3 AS f1, 'C31' AS f2)
           , orig2 AS (SELECT DISTINCT f1, f2 FROM orig)
           , orig3 AS (SELECT f1, f2, row_number() OVER(PARTITION BY f1 ORDER BY f2) AS RowNum FROM orig2)
           , orig4
             -- Use recursion to concatenate the fields
             AS (SELECT f1, CONVERT(VARCHAR(MAX), f2) AS val, rownum
                   FROM orig3
                  WHERE RowNum = 1
                 UNION ALL
                 SELECT orig4.f1, orig4.val + ', ' + orig3.f2 AS val, orig3.rownum
                   FROM orig4
                        INNER JOIN orig3
                          ON orig4.RowNum + 1 = orig3.RowNum
                         AND orig4.f1 = orig3.f1)
        SELECT *
          FROM orig4
         -- select only the rows that match the maximum rownum
         WHERE NOT EXISTS
                 (SELECT 1
                    FROM orig4 o44
                   WHERE o44.f1 = orig4.f1
                     AND o44.rownum > orig4.rownum)
    

    Another approach that works only for sql server would be to build an aggregate CLR function that concatenates the values: http://msdn.microsoft.com/en-us/library/91e6taax%28v=vs.90%29.aspx.

    If you came across this article but you use oracle, you have the option to use the query above or define a custom aggregate function in pl/sql (http://docs.oracle.com/cd/B28359_01/appdev.111/b28425/aggr_functions.htm).

提交回复
热议问题