聚合逗号分隔的数据,分为适当的行

时间:2019-12-30 18:22:41

标签: sql-server tsql

我正在SQL Server 2014中编写一个SQL查询,我需要创建一个查询以返回一个结果集,该结果集在每行中包含一个逗号分隔列表,该列表包含分配给该行中学校的每个区经理。我无法使用SQL Server 2017的String_agg函数。我正在使用使用FOR XML PATHSTUFF的方法,就像该线程中使用的方法:What is the meaning of SELECT ... FOR XML PATH(' '),1,1)?

我的脚本正在生成一个以逗号分隔的列表,但是它正在生成一个包含每个管理员的列表,无论该管理员是否分配给该学校,并且它正在为查询结果中的每一行返回相同的列表,而不是显示仅分配给该学区的管理人员列表。

with district_Managers as 
(
    select
        rtrim(ltrim(CONCAT(p.person_first_name, ' ' , p.person_last_name))) as name,
        m.District_GUID as Manager_district_guid,
        s.District_GUID as School_district_guid,
        d.District_Name,
        s.School_Name, 
        s.school_guid
    from 
        Manager m
    inner join 
        district d on d.District_GUID = m.District_GUID
    inner join 
        person p on m.person_guid = p.person_guid
    inner join 
        school s on s.district_Guid = m.District_GUID
    where 
        m.Manager_position_text = 'DAI' and m.Manager_hire_flag = 'W'
)
select
    (stuff((select ','+ [name] 
            from district_Managers 
            group by Manager_district_Guid 
            for xml path('')), 1, 1, '')) as [Name], 
    School_Name AS [School Name], District_Name AS [District Name],
    (select count(*) 
     from dbo.Manager m 
     where m.district_guid = School_district_guid 
       and m.Manager_position_text = 'DAI' 
       and m.Manager_hire_flag = 'W') AS [Count]
from
    district_Managers
order by 
    [Count] desc, District_Name  

如何将字段中列出的经理限制为分配给学校的经理?

编辑:放置for xml语句

1 个答案:

答案 0 :(得分:2)

您需要将行与外部查询匹配。注意这一行-where csl.School_district_guid = dm.School_district_guid ...我在做一些假设。

with district_Managers as 
    (
        select
        rtrim(ltrim(CONCAT(p.person_first_name, ' ' , p.person_last_name))) as name,
        m.District_GUID as Manager_district_guid,
        s.District_GUID as School_district_guid,
        d.District_Name,
        s.School_Name, 
        s.school_guid
        from Manager m
        inner join district d on d.District_GUID = m.District_GUID
        inner join person p on m.person_guid = p.person_guid
        inner join school s on s.district_Guid = m.District_GUID
        where m.Manager_position_text = 'DAI' and m.Manager_hire_flag = 'W'
    )
    select
    (
        stuff(
        (
            select ','+ [name] 
            from district_Managers csl
            where csl.School_district_guid = dm.School_district_guid
            group by Manager_district_Guid for XML path('')
        ),1,1,'') 

    ) as [Name], School_Name AS [School Name], District_Name AS [District Name],
    (select count(*) from dbo.Manager m where m.district_guid = School_district_guid and m.Manager_position_text = 'DAI' and m.Manager_hire_flag = 'W'
        ) AS [Count]
    FROM district_Managers dm
    Order By [Count] Desc, District_Name 

如果只想获取不同的行,则可以使用SELECT DISTINCT...,也可以在其他列周围使用MAX(),并在逗号分隔的列表中使用GROUP BY