将查询结果行压缩为具有逗号分隔值的列

时间:2011-03-15 22:18:52

标签: sql sql-server sql-server-2005 tsql pivot

我有这个问题:

SELECT 
    HICNo
    ,trr.CUS_ID
    ,TRRRunDate
    ,trr.LastName
    ,trr.FirstName
    ,trr.TRCCode
    ,trr.TRCDescr
    ,trr.TCCode
    ,trr.TRREffDate
    ,PBPID
    ,PriorPBPID
    ,LISLevel
    ,[LIS%]
    ,LISEffDate
    ,CONVERT (CHAR,INE_EV_DT,101) AS EventDate
    ,INE_USER_ID AS UserID
    ,tcl.TCL_TYPE_DESC AS [Description]
FROM 
    #AM_TRR_INS trr                                          
    JOIN ETLStaging.dbo.INS_INSURED ins ON trr.CUS_ID   = ins.INS_CUS_ID
    JOIN ETLStaging.dbo.INE_INSURED_EV ine ON ins.INS_ID = INE.INE_INS_ID
    JOIN ETLStaging.dbo.TCL_TYPE_CD_LOOKUP tcl ON 
            ine.INE_TYPE = tcl.TCL_TYPE_CODE
            AND tcl.TCL_ID = '12'
UNION 
(
    SELECT
        HICNo
        ,trr.CUS_ID
        ,TRRRunDate
        ,trr.LastName
        ,trr.FirstName
        ,trr.TRCCode
        ,trr.TRCDescr
        ,trr.TCCode
        ,trr.TRREffDate
        ,PBPID
        ,PriorPBPID
        ,LISLevel
        ,[LIS%]
        ,LISEffDate
        ,CONVERT (CHAR,INA_PRC_DT,101) AS EventDate
        ,ina.INA_USER_ID AS UserID
        ,tcla.TCL_TYPE_DESC AS [Description]

    FROM 
        #AM_TRR_INS trr                                          
        JOIN ETLStaging.dbo.INS_INSURED ins ON trr.CUS_ID   = ins.INS_CUS_ID
        JOIN ETLStaging.dbo.INA_INSURED_AUD ina ON ins.INS_ID= ina.INA_INS_ID
        JOIN ETLStaging.dbo.TCL_TYPE_CD_LOOKUP tcla ON 
            ina.INA_TYPE = tcla.TCL_TYPE_CODE
            AND tcla.TCL_ID = '12'  
)

返回结果集

  

9876543A 123456789 02/13/2011
    LASTNAME FIRSTNAME 011报名截止日期为61 03/01/2011     002 NULL 02/04/2011 MARKW APPLICATION   9876543A 123456789 02/13/2011
    LASTNAME FIRSTNAME 011报名截止日期为61 03/01/2011     002 NULL 02/08/2011 MARKW新ID卡   9876543A 123456789 02/13/2011
    LASTNAME FIRSTNAME 011报名截止日期为61 03/01/2011     002 NULL 02/08/2011 MCSB473信息   发往CMS 9876543A 123456789 02/13/2011
    LASTNAME FIRSTNAME 011报名截止日期为61 03/01/2011     002 NULL 02/08/2011 MCSB475已收到回复   来自CMS

我正在尝试将结果展平为一行,其中EventDate,UserID和Description列以逗号分隔,结果适合一行,只使用GROUP BY展平所有内容。我被困 - 使用XML PATH和COALESCE不能正常工作我希望......

1 个答案:

答案 0 :(得分:0)