TSQL从连接中连接一列导致多行

时间:2014-10-10 15:26:42

标签: sql sql-server-2008 tsql

我首先想到的是一个简单的concat问题并且使用了STUFF并发现我自己遇到了知识限制,因为多行是来自连接。

我正在阅读的大多数示例都没有任何过滤,或者我错过了如何正确实现它。

我看了this例如。

我正在努力弄清楚如何使用上面的SO帖子等方法获得连接的效果。

我的多行查询:

SELECT 
    [INC].[IN_ID],
    [INC].[SUBJ_LINE],
    [REL].[PEOPLE_ID],
    [ISA].[ISSUE_AREA_ID],
    '######' AS 'SEPERATOR',
    REL.*

FROM 
INCOMING INC

JOIN RELATION REL ON
REL.IN_ID = INC.IN_ID

JOIN [IN_ISSUE_AREA] ISA ON
ISA.IN_ID = INC.IN_ID

WHERE
   INC.METHOD = 'imail'
   AND [INC].[TO_ADDRESS] IS NOT NULL
   AND [INC].[IN_ID] = 5421121

结果:

IN_ID | SUBJ_LINE | PEOPLE_ID | ISSUE_AREA_ID | SEPERATOR | .....
 542      SubjA      72          IssueA          ######
 542      SubjA      72          IssueJ          ######

我希望看到的是:

IN_ID | SUBJ_LINE | PEOPLE_ID | ISSUE_AREA_ID  | SEPERATOR | .....
 542      SubjA      72         IssueA, IssueJ    ######

谢谢

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
    [INC].[IN_ID],
    [INC].[SUBJ_LINE],
    [REL].[PEOPLE_ID],
    STUFF( 
       (SELECT CAST(', ' + ISSUE_AREA_ID  AS VARCHAR(MAX)) 
         FROM IN_ISSUE_AREA
         WHERE (IN_ID= inc.IN_ID) 
         FOR XML PATH ('')
      ),1,2,'') 
    AS [ISSUE_AREA_ID],
    '######' AS 'SEPERATOR'

FROM 
INCOMING INC

JOIN RELATION REL ON
REL.IN_ID = INC.IN_ID

WHERE
   INC.METHOD = 'imail'
   AND [INC].[TO_ADDRESS] IS NOT NULL
   AND [INC].[IN_ID] = 5421121

答案 1 :(得分:0)

您是否尝试将值插入临时表或使用CTE,然后使用FOR XML PATH...串联技巧播放内容?这就是临时表的样子:

CREATE TABLE #This
( IN_ID         INT
 ,SUBJ_LINE     VARCHAR(50)
 ,PEOPLE_ID     INT
 ,ISSUE_AREA_ID VARCHAR(50)
 ,SEPERATOR     VARCHAR(50))

-- USE YOUR DATA AND JOINS TO INSERT THE INFO, IN PLACE OF THESE TWO LINES
INSERT #This VALUES (542,'SubjA',72,'IssueA','######')
INSERT #This VALUES (542,'SubjA',72,'IssueJ','######')

SELECT
     IN_ID
    ,SUBJ_LINE
    ,PEOPLE_ID
    ,LEFT(( SELECT ISSUE_AREA_ID + ', '
            FROM #This M2
            WHERE   M2.IN_ID = M1.IN_ID
                AND M2.SUBJ_LINE = M1.SUBJ_LINE
                AND M2.PEOPLE_ID = M1.PEOPLE_ID
                AND M2.SEPERATOR = M1.SEPERATOR
            ORDER BY ISSUE_AREA_ID
            FOR XML PATH('')
           )
        ,LEN((SELECT ISSUE_AREA_ID + ', ' 
              FROM #This M2
              WHERE M2.IN_ID = M1.IN_ID
                AND M2.SUBJ_LINE = M1.SUBJ_LINE
                AND M2.PEOPLE_ID = M1.PEOPLE_ID
                AND M2.SEPERATOR = M1.SEPERATOR
              ORDER BY ISSUE_AREA_ID
              FOR XML PATH('')
             ))-LEN(', '))              AS ISSUE_AREA_ID
    ,SEPERATOR
FROM #This M1
GROUP BY
     IN_ID
    ,SUBJ_LINE
    ,PEOPLE_ID
    ,SEPERATOR

DROP TABLE #This