declare @sql varchar(2000) set @sql='select CONVERT(varchar(100), a.[Time], 23) as 时间,count(b.title) as 总数' select @sql =@sql+ ',sum(case b.title when '''+Title+''' then 1 else 0 end) as '+'['+Title+']' from (select distinct title from B) as B set @sql=@sql+' from A as a left join B as b on a.AId=B.Aid group by CONVERT(varchar(100), a.[Time], 23) order by CONVERT(varchar(100), a.[Time], 23) desc' exec(@sql)