日期:2014-05-18 浏览次数:20494 次
create table tbGuestBook(BookNameId varchar(8),[Message] varchar(20)) insert into tbGuestBook select '[军事]','aaaaaa1' union all select '[军事]','ddaadassd1' union all select '[军事]','ffff1' union all select '[博文]','ffggghhhh3' union all select '[博文]','ffggghhhh3' union all select '[博文]','dffd3' union all select '[健康]','tttefff5' union all select '[健康]','ffggghhhh5' union all select '[文物]','dsfdsfdsf6' union all select '[文物]','ffggghhhh6' union all select '[其他]','eeeeeeee8' union all select '[其他]','ddddddd8' union all select '[其他]','sfdfdfsd8' union all select '[其他]','fgghf8' union all select '[其他]','dfgdf8' select BookNameId, stuff((select ','+[Message] from tbGuestBook where BookNameId = e.BookNameId for xml path('')),1,1,'') as BookNameList from tbGuestBook E group by BookNameId /* BookNameId BookNameList ---------- --------------------------------------------- [博文] ffggghhhh3,ffggghhhh3,dffd3 [健康] tttefff5,ffggghhhh5 [军事] aaaaaa1,ddaadassd1,ffff1 [其他] eeeeeeee8,ddddddd8,sfdfdfsd8,fgghf8,dfgdf8 [文物] dsfdsfdsf6,ffggghhhh6 */ --加上top 2 不就ok了吗? select BookNameId, stuff((select top 2 ','+[Message] from tbGuestBook where BookNameId = e.BookNameId for xml path('')),1,1,'') as BookNameList from tbGuestBook E group by BookNameId /* BookNameId BookNameList ---------- ----------------------------- [博文] ffggghhhh3,ffggghhhh3 [健康] tttefff5,ffggghhhh5 [军事] aaaaaa1,ddaadassd1 [其他] eeeeeeee8,ddddddd8 [文物] dsfdsfdsf6,ffggghhhh6 */