通过分隔为逗号将所有数据合并为单个

时间:2018-11-08 22:19:25

标签: sql sql-server

这是我的查询

SELECT 
    FACT.Id fActivityId, FACT.ActivityName,
    ACT.fOrganizationRegion_Id, ACT.Id AS ActivityId, ACT.CreateUserId,
    (US.LastName + ',' +US.FirstName) AS UserName,
    REG.Id AS RegionId, REG.OrganizationName AS RegionName,
    ORG.Id AS OrganizationId, ORG.OrganizationName AS OrganizationName,
    FC.Id AS FundingSourceId, fc.FundingSource,
    CA.Id AS CoverageAreaId, CA.County, CA.ZipCode
FROM 
    Activities ACT
JOIN 
    fActivity FACT ON FACT.Id = ACT.fActivity_Id
JOIN
    fOrganizationRegion ORGREG ON ORGREG.Id = ACT.fOrganizationRegion_Id
JOIN 
    fOrganization REG ON REG.Id = ORGREG.RegionOrg_Id
JOIN 
    fOrganization ORG ON ORG.Id = ORGREG.Org_Id
JOIN 
    ActivityFundingSource AFC ON AFC.Activity_Id = ACT.Id
JOIN 
    fFundingSource FC ON FC.Id = AFC.FundingSource_Id
JOIN 
    ActivityCoverageArea ACA ON ACA.Activity_Id = ACT.Id
JOIN 
    fCoverageAreas CA ON CA.Id = ACA.CoverageArea_Id
JOIN 
    Users US ON US.UserId  = ACT.CreateUserId
LEFT JOIN 
    fInterventionType ITYPE ON ITYPE.Id = FACT.InterventionType_Id
LEFT JOIN 
    ActivityInterveningVariable AIVAR ON AIVAR.Activity_Id = ACT.Id
LEFT JOIN 
    fInterveningVariables IVAR ON IVAR.Id = AIVAR.fInterveningVariable_Id
LEFT JOIN 
    ActivitySecondaryPriorityProblem ASPP ON ASPP.Activity_Id = ACT.Id
LEFT JOIN 
    fPriorityProblem PP ON PP.Id = ASPP.fPriorityProblem_Id
LEFT JOIN 
    fMethodApproach MA ON MA.Id = ACT.fMethodApproach_Id
LEFT JOIN 
    fStrategyMethodApproach  SMA ON SMA.fMethodApproach_Id = MA.Id
LEFT JOIN 
    fStrategy ST ON ST.Id = SMA.fStrategy_Id
LEFT JOIN 
    ActivityTargetPopulation ATP ON ATP.Activity_Id = ACT.Id
LEFT JOIN 
    fTargetPopulation TP ON TP.Id = ATP.TargetPopulation_Id

我的结果集如下屏幕截图

enter image description here

我的问题是我想将所有基于ActivityId的记录合并在一起,并以红色突出显示为单个记录。

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试一下:

select 
    activityID, 
    string_agg(country,',') as country, 
    string_agg(cast(zipcode as varchar(10)),',') as Zipcode
from YourTableName
group by activityID
  • 您必须具有SQL Server 2017或更高版本
  • string_agg仅适用于字符串