select * from ( select isnull(c.type,'其他') type,d from ( select ID,Record_code,code,day(thedate) d from search_record where (Name!='' or Phone!='')--判断姓名或电话不为空 ) zx join customer c on zx.code=c.code ) a pivot (count(d) for d in([1],[13]))n alter proc tj_khlb_zxl_rq @zxsj1 datetime ,--咨询时间开始,不能为空 @zxsj2 datetime,--咨询时间结束,不能为空 as declare @sql Nvarchar(4000) select @sql=isnull(@sql+',','')+'['+cast(d as varchar(2))+']' from (select distinct day(thedate) d from search_record) n set @sql=' select * from ( select isnull(c.type,''其他'') type,d from ( select ID,Record_code,code,day(thedate) d from search_record where (Name!='''' or Phone!='''') and (thedate between @st and @en ) ) zx join customer c on zx.code=c.code ) a pivot (count(d) for d in('+@sql+'))n ' exec sp_executesql @sql,N'@st datetime,@en datetime',@zxsj1,@zxsj2