我想合并一些行

时间:2019-09-04 18:06:50

标签: sql sql-server concatenation for-xml-path

我正在查看的应用程序数据中,每个数据库条目仅允许使用100个字符的自由文本。如果超过100,则会在数据库中创建一个新行。

我已经研究了这个解决方案并尝试实现它。它没有按我预期的那样工作。 How to concatenate text from multiple rows into a single text string in SQL server?

Data Structure:
NAME_ID     NAME    ATXR_SOURCE_ID  ATSY_ID ATXR_DESC   Note
500 Jane    463495.0251 ATN0    Affiliation Add                                                         dfsdfsfdsafdsadfsadfdsafsadsfdasfd
500 Jane    463495.0251 ATN0    Affiliation Add                                                         asdfdsfdsafdafdasdfsadfsadfsadfadfsa
500 Jane    463495.0251 ATN0    RITM0072237                                                             Update to record
500 Jane    463495.0251 ATN0    RITM0074636                                                             Script update
500 Jane    463495.0251 ATN0    RITM0079507                                                             Services updated




SELECT DISTINCT ST2.NAME_ID, ST2.NAME, ST2.ATXR_DESC, ST2.Note,
    SUBSTRING(
        (
            SELECT NAME_ID, NAME, ATXR_SOURCE_ID, ATSY_ID, ATXR_DESC, ','+ Note  AS [text()]
            FROM #Notes ST1
            WHERE ST1.ATXR_DESC = ST2.ATSY_ID
            ORDER BY ST1.Note
            FOR XML PATH ('')
        ), 2, 1000) [Students]
FROM #Notes ST2

Actual:
NAME_ID     NAME    DESC    Note    Students
500 Jane    Affiliation Add                                                         dfsdfsfdsafdsadfsadfdsafsadsfdasfd  NULL
500 Jane    Affiliation Add                                                         asdfdsfdsafdafdasdfsadfsadfsadfadfsa    NULL
500 Jane    TicketA Update to record    NULL
500 Jane    TicketB Script update   NULL
500 Jane    TicketC Services updated    NULL

预期(对于第1行和第2行,我希望注释被“串联”):

NAME_ID     NAME    DESC    Note    Students
500 Jane    Affiliation Add                                                         dfsdfsfdsafdsadfsadfdsafsadsfdasfdasdfdsfdsafdafdasdfsadfsadfsadfadfsa  NULL
500 Jane    TicketA Update to record    NULL
500 Jane    TicketB Script update   NULL
500 Jane    TicketC Services updated    NULL

1 个答案:

答案 0 :(得分:0)

如果使用SQL Server 2017+,则可以使用SRING_AGG()方法:

https://docs.microsoft.com/de-de/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

SELECT t.NAME_ID,
  t.NAME,
  t.ATXR_DESC,
  STRING_AGG(t.Note,'') AS Note
FROM <TABLE> AS t
GROUP BY t.NAME_ID,
    t.NAME,
    t.ATXR_DESC

-- result:
--NAME_ID   NAME    ATXR_DESC           Note
--500       Jane    Affiliation Add     asdfdsfdsafdafdasdfsadfsadfsadfadfsadfsdfsfdsafdsadfsadfdsafsadsfdasfd
--500       Jane    RITM0072237         Update to record
--500       Jane    RITM0074636         Script update
--500       Jane    RITM0079507         Services updated

访问以下帖子: How to concatenate text from multiple rows into a single text string in SQL server?

如果使用旧版SQL Server,则可以实现用于字符串连接的程序集:Does T-SQL have an aggregate function to concatenate strings?