有表tb1,tb2
表tb1内容ID       时间      参加人数 
1     2007-12-1    100         
2     2007-12-1    ..
3     2009-12-1    ..
4     2008-12-1    ..
5     2008-12-1    .. tb2
ID   名称    表tb1 ID
1    张三       1  
2    张四       1   
3    张五       4  
4    张三       1
5    张五       5  ....................要求是,求出各年参加培训次数最多的人如结果2007年      张三     2次  
2008年      张五     2次   
   我的做法是先 查询年份select distinct year(年) as x_date from tb1 order by x_date desc然后用查询结果在页面循环查询tb2select top 1 count(b.名称) as tdm from tb1 as a, tb2 as b where  A.ID=B.Id AND  year(A.x_date) ="年" 
效果不好,不太会写,谢谢。存储过程怎么写,谢谢

解决方案 »

  1.   

    select *,count(tb1.id)  from tb1, tb2 where tb1.id=tb2.id group by year ,tb1.id
      

  2.   


    create table #tb1(ID int,tDate datetime, Num int)
    insert #tb1 
    select 1, '2007-12-1',100 union all
    select 2, '2007-12-1',99 union all
    select 3, '2009-12-1',98 union all
    select 4, '2008-12-1',99 union all
    select 5, '2008-12-1',100
    create table #tb2(ID int,uname varchar(20), t1ID int)
    insert into #tb2
    select 1, '张三',1 union all
    select 2, '张四',1 union all
    select 3, '张五',4 union all
    select 4, '张三',1 union all
    select 5, '张五',5 create procedure getall
    as
    select * from #tb1 inner join #tb2 on #tb1.id=#tb2.t1id
    exec getall
    --1 2007-12-01 00:00:00.000 100 1 张三 1
    --1 2007-12-01 00:00:00.000 100 2 张四 1
    --4 2008-12-01 00:00:00.000 99 3 张五 4
    --1 2007-12-01 00:00:00.000 100 4 张三 1
    --5 2008-12-01 00:00:00.000 100 5 张五 5
    create procedure getmax
    as
    ;with cte1 as
    (
    select tDate,uname,count(uname) as tcount
    from #tb1 inner join #tb2 on #tb1.id=#tb2.t1id
    group by uname,tDate
    )
    declare @i int
    set @i=(select max(tcount) from cte1)
    select tDate,uname, tcount
    from cte1
    where tcount=@i
      

  3.   

    select year(时间),名称,count(*) as 次数
    from tb1 ,tb2 where tb1.id=tb2. 表tb1ID
    group by year(时间),名称
    having count(*)>=
    (select count(*) from tb1 a,tb2 b
    where a.id=b.表tb1ID 
    and  year(a.时间)=year(tb1.时间)
    group by year(a.时间),b.名称)