日期:2014-05-19  浏览次数:20431 次

在找分组后最大一组的值时,如何将临时表换成子查询?
/*

create   table   Days
(
DayId   int   identity(1,   1)   primary   key,  
DayCount   int,  
DayWeek   int  
)

insert   Days(DayCount,   DayWeek)  
select   1,   1   union   all  
select   2,   1   union   all  
select   3,   1   union   all  
select   4,   1   union   all  
select   5,   1   union   all  
select   6,   1   union   all  
select   7,   1   union   all  
select   8,   1   union   all  
select   9,   1   union   all  
select   10,   1   union   all  
select   11,   1   union   all  
select   12,   1   union   all  
select   13,   2   union   all  
select   14,   2   union   all  
select   14,   3   union   all  
select   14,   3   union   all  
select   14,   3   union   all  
select   14,   4   union   all  
select   14,   4   union   all  
select   14,   4

*/

select   DayWeek,   sum(DayCount)   as   DayCount   into   #temp   from   Days   where   DayWeek   >   1   group   by   DayWeek

select   *   from   #temp

/*

DayWeek DayCount
2 27
3 42
4 42

*/

select   top   1   *   from  
(select   a.DayWeek,   a.DayCount   from   #temp   a   inner   join  
(select   max(DayCount)   as   DayCount   from   #temp)   b   on   a.DayCount   =   b.DayCount)   aa   order   by   aa.DayWeek

/*

DayWeek DayCount
3 42

*/


/*

drop   table   Days

*/

------解决方案--------------------
用第二句的
------解决方案--------------------
select top 1 DayWeek,DayCount as DayCount from
(
select top 100 percent DayWeek, sum(DayCount) as DayCount from Days where DayWeek > 1 group by DayWeek order by DayCount desc
)a