select date,sum(case name when 'Mike' then 1 else 0 end) as [Mike 出现次数]
           ,sum(case name when 'John' then 1 else 0 end) as [John 出现次数]
           ,sum(case name when 'Alex' then 1 else 0 end) as [Alex 出现次数]
from 你的表
group by date

解决方案 »

  1.   

    你先试一下下面的语句,我没试,因为我这里没有环境select date,(case  when 'Mike' then count(Name) end) as Mike出现次数,
    ,(case  when 'John' then count(Name) end) as John出现次数,
    ,(case  when 'Alex' then count(Name) end) as Alex出现次数 from table group by date
      

  2.   

    多谢了, 好快啊!
    出于好奇,我想再问一句: 如果不知道Name里倒底有多少可能性的话,怎么把全部的人的出现次数查出来呢?
      

  3.   

    是不是一定要用外部程序来组装sql语句了呢?
      

  4.   

    那就用动态生成SQL语句的方法:declare @sql varchar(8000),@name varchar(20)
    set @sql='select date'
    declare #aa cursor for select distinct name from 你的表
    open #aa
    fetch next from #aa into @name
    while @@fetch_status=0
    begin
      set @sql=@sql+char(13)+',sum(case name when '''+@name
               +''' then 1 else 0 end) as ['+@name+' 出现次数]'
      fetch next from #aa into @name
    end
    close #aa
    deallocate #aa
    set @sql=@sql+char(13)+'from 你的表 group by date'
    exec (@sql)