2013-10-23 44 views
1

我有一个SQL Server 2008存储过程与联接返回多行:TSQL合并多个行和列

default ~// NULL NULL NULL Lorem 
default ~// NULL NULL NULL Ipsum 

,我想作为一个与最后一列合并这两行返回:

default ~// NULL NULL NULL Lorem, Ipsum 

我的步骤如下

BEGIN 
    SET NOCOUNT ON; 

    SELECT 
      p.display_name AS Name, 
      p.url AS Url, 
      ISNULL(REPLACE(parentPage.url,'~','') + parentPage.alias,REPLACE(p.url,'~','')) as ParentPageURL, 
      p.page_image AS PageImage, 
      p.synopsis AS Synopsis, 
      p.metatitle AS Metatitle, 
      t.tag_name as tag 

      FROM page p 
      LEFT JOIN page parentPage on parentPage.id = p.parentid 
      LEFT JOIN page_features pf on p.id = pf.pageid and (pf.feature_type = 'TEXT' OR pf.feature_type = 'BLOG') 
      JOIN dbo.tag_collection_tag tc on tc.tag_collection_id = p.tag_collection_id 
      JOIN dbo.tag t on t.id = tc.tag_id 
      JOIN dbo.[Split](UPPER(@tags),',') Split on UPPER(t.tag_name) like '%' + split.Data + '%' 

    WHERE p.status = 'PUBLISHED' 
    AND p.include_in_nav = 1 
    AND (p.pagelevel = @level OR @level IS NULL) 
    AND (p.section_id = @sectionId OR @sectionId IS NULL) 
    ORDER BY ISNULL(REPLACE(parentPage.url,'~','') + parentPage.alias,REPLACE(p.url,'~','')) 

END 

谢谢。

+1

使用'FOR XML PATH'子句。这里是一个例子:http://stackoverflow.com/questions/6888432/concatenate-with-xml-path – Konza

回答

1

请注意,如果您在表格页面中有列ID。应该使用它代替display_name

;WITH a as 
(
SELECT 
     /*p.id,*/ 
     p.display_name AS Name, 
     p.url AS Url, 
     ISNULL(REPLACE(parentPage.url,'~','') + parentPage.alias,REPLACE(p.url,'~','')) as ParentPageURL, 
     p.page_image AS PageImage, 
     p.synopsis AS Synopsis, 
     p.metatitle AS Metatitle, 
     t.tag_name as tag, 
     ISNULL(REPLACE(parentPage.url,'~','') 
     + parentPage.alias,REPLACE(p.url,'~','')) XXX 
     FROM page p 
     LEFT JOIN page parentPage on parentPage.id = p.parentid 
     LEFT JOIN page_features pf on p.id = pf.pageid and (pf.feature_type = 'TEXT' OR pf.feature_type = 'BLOG') 
     JOIN dbo.tag_collection_tag tc on tc.tag_collection_id = p.tag_collection_id 
     JOIN dbo.tag t on t.id = tc.tag_id 
     JOIN dbo.[Split](UPPER(@tags),',') Split on UPPER(t.tag_name) like '%' + split.Data + '%' 

WHERE p.status = 'PUBLISHED' 
AND p.include_in_nav = 1 
AND (p.pagelevel = @level OR @level IS NULL) 
AND (p.section_id = @sectionId OR @sectionId IS NULL) 
) 
SELECT Name, Url, ParentPageURL, PageImage, Synopsis, Metatitle 
    ,STUFF(( 
     select ',' + [tag] 
     from a t1 
     -- I assume display_name is unique. I would use page.id, 
     -- but I am not sure you have that column 
     -- t1.id = t.id 
     where t1.display_name = t.display_name 
     for xml path(''), type 
    ).value('.', 'varchar(max)'), 1, 1, '') [tags] 
from a t 
group by Name, Url, ParentPageURL, PageImage, Synopsis, Metatitle 
ORDER BY XXX