admin

合并SQL中的列

sql

我正在使用SQL Server 2017,其中有一个存储过程,其中有一个简单的选择,如联接:

SELECT
      [p].[legacyKey] AS JobNumber
    , [p].[Name] AS JobName
    , [G].[Label] AS DesignStatus
    , [GS].[Description]  AS ShopStatus
    , [JN].Title
    , [JN].Note
    , 'Remove' AS [Remove]
      FROM [Project] AS [P]
          INNER JOIN [Customer] AS [c] ON [P].[CustomerSoldById] = [C].[CustomerKey]
          INNER JOIN [General] AS [G] ON [P].[StatusKey] = [G].[GeneralKey]
          INNER JOIN [General] AS [GS] ON [P].[ShopsStatus] = [GS].[GeneralKey]
          INNER JOIN ProjectDesign AS PD ON P.ProjectKey = PD.ProjectKey
          INNER JOIN DESIGN AS D ON PD.DesignKey = D.DesignKey
          INNER JOIN JobNotes AS JN ON PD.DesignKey = JN.DesignKey
      WHERE [G].[Extended] = 'Project Status'
      and p.LegacyKey = 18213

该查询的结果是:

+-----------+----------+--------------+------------+--------+-------------------+--------+
| JobNumber | JobNAme  | DesignStatus | ShopStatus | Title  |       Note        | Remove |
+-----------+----------+--------------+------------+--------+-------------------+--------+
|      1234 | TestName | Correct      | Inc        | Title1 | Note test design  | Remove |
|      1234 | TestName | Correct      | Inc        | Title2 | note test proyect | Remove |
+-----------+----------+--------------+------------+--------+-------------------+--------+

如您所见,除TitleNote列外,所有列都完全相同,是否可以合并“标题”和“注释”以获得仅一列而不是两列?,例如:

+-----------+----------+--------------+------------+--------------------------------------------------------------+--------+--+
| JobNumber | JobNAme  | DesignStatus | ShopStatus |                             Note                             | Remove |  |
+-----------+----------+--------------+------------+--------------------------------------------------------------+--------+--+
|      1234 | TestName | Correct      | Inc        | Title1 : Note test design \n , Title2 : note test proyect \n | Remove |  |
+-----------+----------+--------------+------------+--------------------------------------------------------------+--------+--+

我尝试

CONCAT([JN].[Title], ': ', STRING_AGG([JN].[Note], '\N'))

但是它只是titlenote列合并列,但没有合并第1行和第2行,我在做什么错呢?问候


阅读 146

收藏
2021-06-07

共1个答案

admin

concat()然后使用string agg()

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=69806c24356e5ef86fd0bfa7a239c82b

编辑1:如果您不希望/n字符串中的最后一个值,则可以执行以下操作:

select left(string,len(string)-3) from ( SELECT STRING_AGG(CONCAT(Title, ': ', Note, ' \n'),', ') as string from test ) t

编辑2:如果您有多个职位编号,并且不希望所有值都汇总到一行,则可以执行以下操作:

select left(string,len(string)-3) from ( SELECT STRING_AGG(CONCAT(Title, ': ', Note, ' \n'),', ') WITHIN GROUP (ORDER BY JobNumber) as string from test group by JobNumber ) t

2021-06-07