日期:2014-05-16  浏览次数:20466 次

统计每个部门中有多少人有某个项目
 select * from 
 PeisPatientConclusion
 inner join
 PeisPatient
 on 
 PeisPatientConclusion.ID_Patient=PeisPatient.ID_Patient
 where Org_Name  is not null
 and DateFinalExamed>'2013-01-01' and DateFinalExamed<'2013-12-31'
 and Conclusion_Name_R like '%峨眉山%'
 order by Org_Name

语句只能统计出2013年所有单位旅游者去过峨眉山,我想统计出每一个单位有那些人去过峨眉山

单位          姓名
中国移动      张三 李四 王二
中国电信      赵武  王六

其中DateFinalExamed字段为时间,Org_Name字段为单位名称,PatientName字段为姓名,请各位前辈指点指点,最好能贴上代码,不胜感激。
------解决方案--------------------
修改一下:
;with t
as
(
select Org_Name,姓名 from 
  PeisPatientConclusion
  inner join
  PeisPatient
  on 
  PeisPatientConclusion.ID_Patient=PeisPatient.ID_Patient
  where Org_Name  is not null
  and DateFinalExamed>'2013-01-01' and DateFinalExamed<'2013-12-31'
  and Conclusion_Name_R like '%峨眉山%'
)


select distinct
       Org_Name,
       replace(STUFF((select ','+姓名 from t t2 
                      where t2.Org_Name = t1.Org_Name 
                      for xml path('')
                      ),1,1,''),',',' ')
from t t1

------解决方案--------------------
加个distinct

引用:
前辈,你回答我上一篇帖子的语句运行出来很多重复值
如下贴图
我想要的效果是
部门      出现次数    人员     出现次数
财务室      22        张三      20
财务室      22        李四      2
这样就可以了,帖子地址是
http://bbs.csdn.net/topics/390720895?page=1#post-396855220
能麻烦你帮忙改下吗?