sql 一对多查询

1. 一对多查询

查询departmentinfo字典下所有部门的人员数量

select * from departmentinfo a left join (select count(*) UserCount,UnitId from ReCharge where ReDate='2017-06-15' group by UnitId) b on (a.DepartMentId=b.UnitId) order by a.sort

2.将查询出来的结果 的 某列 用逗号隔开 作为新字符串

SELECT STUFF(( SELECT ',' + Name
FROM CollectDocument where archivepeople='xxxx' and z_fileno like 'N%'
FOR
XML PATH('')
), 1, 1, '') AS Name

对比

select * from CollectDocument where archivepeople='xxxx' and z_fileno like 'N%'

查询结果:

原文地址:https://www.cnblogs.com/hpbkin/p/7018593.html