日期:2014-05-18 浏览次数:20766 次
;with f as ( select convert(varchar(10),b.loginTime,120) as 日期,isnull(count(distinct a.username),0) as 人数,a.username as 登入人 from user a left join task b on a.taskID=b.taskID ) select 日期,人数, [登入人]=stuff((select ','+[value] from f where 日期=t.日期 for xml path('')), 1, 1, '') from f t group by 日期,人数
------解决方案--------------------
create table [user](username varchar(10),taskid int) insert into [user] select '张三',1 union select '张三',2 union select '张三',3 union select '李四',4 create table task(taskid int,loginTime datetime) insert into task select 1,'2012-12-23 11:30:00' union select 2,'2012-12-23 18:30:00' union select 3,'2012-12-25 11:30:00' union select 4,'2012-12-23 11:00:00' declare @bdate datetime=(select min(loginTime) from task), @edate datetime=(select MAX(loginTime) from task) ;with cte1 as ( select 日期=DATEADD(day,number,@bdate) from master.dbo.spt_values where type='p' and number<=DATEDIFF(DAY,@bdate,@edate) ) ,cte2 as ( select a.username,b.loginTime from [user] a,task b where a.taskid=b.taskid ) select 日期, 人数=(select COUNT(distinct username) from cte2 where DATEDIFF(DAY,a.日期,loginTime)=0), 登入人=isnull(stuff((select distinct ','+username from cte2 where DATEDIFF(DAY,a.日期,loginTime)=0 for xml path('')),1,1,''),'无') from cte1 a /* 日期 人数 登入人 ----------------------- ----------- ------------- 2012-12-23 11:00:00.000 2 李四,张三 2012-12-24 11:00:00.000 0 无 2012-12-25 11:00:00.000 1 张三