日期:2014-05-17 浏览次数:20535 次
IF OBJECT_ID('FilmInfo') Is Not Null Drop Table FilmInfo Create Table FilmInfo (ID Int, filmBaseInfoid Int, MakeType Varchar(10)) Insert Into FilmInfo Select 1, 1, '3D' Union All Select 2, 1, '2D' Union All Select 3, 1, 'IMAX' Union All Select 4, 2, '2D' Union All Select 5, 2, 'IMAX' Union All Select 6, 3, '3D' IF OBJECT_ID('FilmBaseInfo') Is Not Null Drop Table FilmBaseInfo Create Table FilmBaseInfo (ID Int, FilmName Varchar(20)) Insert Into FilmBaseInfo Select 1, '变形金刚3' Union All Select 2, '阿凡达' Union All Select 3, '笔仙' Select A.ID, A.FilmName, B.MakeTypes From FilmBaseInfo A Left Join ( SELECT DISTINCT filmBaseInfoid, STUFF( ( SELECT '/'+MakeType FROM FilmInfo t WHERE filmBaseInfoid = FilmInfo.filmBaseInfoid FOR XML PATH('') ), 1, 1, '' ) AS MakeTypes FROM FilmInfo ) B On A.ID = B.filmBaseInfoid /* ID FilmName MakeTypes ----------- -------------------- ---------------- 1 变形金刚3 3D/2D/IMAX 2 阿凡达 2D/IMAX 3 笔仙 3D */
------解决方案--------------------
IF OBJECT_ID('FilmInfo') Is Not Null Drop Table FilmInfo Create Table FilmInfo (ID Int, filmBaseInfoid Int, MakeType Varchar(10)) Insert Into FilmInfo Select 1, 1, '3D' Union All Select 2, 1, '2D' Union All Select 3, 1, 'IMAX' Union All Select 4, 2, '2D' Union All Select 5, 2, 'IMAX' Union All Select 6, 3, '3D' IF OBJECT_ID('FilmBaseInfo') Is Not Null Drop Table FilmBaseInfo Create Table FilmBaseInfo (ID Int, FilmName Varchar(20)) Insert Into FilmBaseInfo Select 1, '变形金刚3' Union All Select 2, '阿凡达' Union All Select 3, '笔仙' ;WITH TB AS ( SELECT A.ID,A.FilmName,B.MakeType FROM FilmBaseInfo A INNER JOIN FilmInfo B ON A.ID = B.filmBaseInfoid ) select id,FilmName, [MakeTypeS]=stuff((select ','+[MakeType] from TB t where id=tb.id for xml path('')), 1, 1, '') from TB group by id ,FilmName /* id FilmName MakeTypeS ----------- -------------------- ---------------------------------------------------------------------------------------------------------------- 1 变形金刚3 3D,2D,IMAX 2 阿凡达 2D,IMAX 3 笔仙 3D (3 行受影响) */