sqlserver分组统计合并

---分组partition by;统计:Count();合并:for xml path('')
with cte as(
select COUNT(t2.Id) OVER(PARTITION BY t2.Id) as Count,t1.Contact,t1.OrderNo
,t2.Name,t2.Wechat,t2.Id from B_BusinessOrder t1 join Sys_User t2
on t1.UserId=t2.Id where DATEDIFF(d,GETDATE(),DepartureDate)=3 
and t1.IsDeleted=0 and t1.[States]=2 and t2.IsDeleted=0 
),cte2 as (
select distinct Id,(SELECT Contact+'-'+OrderNo+',' FROM cte 
WHERE Id=t3.Id FOR XML PATH('')) as Contact,Name,Wechat,Count from cte t3 
)select LEFT(Contact,len(Contact)-1) as Contact,Name,Wechat,Count from cte2

 

posted @ 2017-03-27 16:01  自由的鱼  阅读(2496)  评论(0编辑  收藏  举报