Sql Server retrieve last date for multiple records -


i have table 5 columns emp, surname, csd, term rsn , date. first 4 columns stay same date change eg. there can 30 records emp 30 different dates.

this code works when add [date] select returns 30 records whereas trying return 1 record last date

create  procedure testpro(     @reportstartdate date, @reportenddate date     )     begin       select distinct emp, surname, csd, case when csd<= @reportstartdate   case when [term rsn] != 0 case when [date] <= @reportenddate (datediff(dd,@reportstartdate, [date]) - (2*  datediff(wk,@reportstartdate,[date])))+1 else (datediff(dd,@reportstartdate, @reportenddate) - (2*  datediff(wk,@reportstartdate,@reportenddate)))+1 end  else (datediff(dd,@reportstartdate, @reportenddate) - (2*  datediff(wk,@reportstartdate,@reportenddate)))+1 end   else   case when [term rsn] != 0  case when [date] <= @reportenddate (datediff(dd,csd, [date]) - (2*  datediff(wk,csd,[date])))+1 else (datediff(dd,csd, @reportenddate) - (2*  datediff(wk,csd,@reportenddate)))+1 end else (datediff(dd,csd, @reportenddate) - (2*  datediff(wk,csd,@reportenddate)))+1 end   end [working days]  gypremiumstemp csd < @reportenddate , [date] >  @reportstartdate --and [date] = (select max([date]) gypremiumstemp) order emp asc end       exec  testpro '2012-01-01', '2012-12-31' 

write below:

create  procedure testpro(     @reportstartdate date, @reportenddate date     )     begin   select emp, surname, csd,[working days] , max(date) [date] ( select distinct emp, surname, csd, case when csd<= @reportstartdate   case when [term rsn] != 0 case when [date] <= @reportenddate (datediff(dd,@reportstartdate, [date]) - (2*  datediff(wk,@reportstartdate,[date])))+1  else (datediff(dd,@reportstartdate, @reportenddate) - (2*  datediff(wk,@reportstartdate,@reportenddate)))+1 end   else (datediff(dd,@reportstartdate, @reportenddate) - (2*  datediff(wk,@reportstartdate,@reportenddate)))+1 end   else   case when [term rsn] != 0  case when [date] <= @reportenddate (datediff(dd,csd, [date]) - (2*  datediff(wk,csd,[date])))+1  else (datediff(dd,csd, @reportenddate) - (2*  datediff(wk,csd,@reportenddate)))+1 end  else (datediff(dd,csd, @reportenddate) - (2*  datediff(wk,csd,@reportenddate)))+1 end   end [working days],[date] -- add dates here  gypremiumstemp csd < @reportenddate , [date] >  @reportstartdate ) t group emp, surname, csd,[working days]  order emp asc end   exec  testpro '2012-01-01', '2012-12-31' 

check demo here.


Comments

Popular posts from this blog

.htaccess - htaccess convert request to clean url and add slash at the end of the url -

C# random value from dictionary and tuple -

algorithm - Testing tetrahedron-triangle intersection -