select identity(int,1,1) id,* into # from 表select code,department,year,(select top 1 mb from # where code=tem.code and department=tem.department and year=tem.year order by id desc),sum(md) md,sum(mc) mc,(select top 1 me from # where code=tem.code and department=tem.department and year=tem.year order by id) from # tem group by code,department,yeardrop table #

解决方案 »

  1.   

    select identity(int,1,1) xh,* into #t from 表select code,department,year,sum(md),sum(mc)
         ,(select top 1 md from #t bb where aa.code=bb.code and aa.department=bb.department and aa.year=bb.year order by xh )
         ,(select top 1 me from #t bb where aa.code=bb.code and aa.department=bb.department and aa.year=bb.year order by xh desc)
      from #t aa
      group by code,department,year
      

  2.   

    select identity(int,1,1) id,* into #temp from 表
    select code,department,year,(select top 1 mb from #temp where code=tem.code and department=tem.department and year=tem.year order by id desc),sum(md) md,sum(mc) mc,(select top 1 me from #temp where code=tem.code and department=tem.department and year=tem.year order by id) from #temp tem group by code,department,year
    drop table #temp