Average of Top n per Group SQL Server

0

Please login or register to vote for this query.

(click on this box to dismiss)

Physical Fitness Meta

Q&A about the site for physical fitness professionals, athletes, trainers, and those providing health-related needs

declare @T table
(
  OpID int,
  ProcessMin float,
  Datestamp datetime
)
insert into @T(OpID, ProcessMin) values
(602,   33),
(602,   36),
(602,   37),
(602,   39),
(602,   41),
(602,   42),
(602,   49),
(602,   51),
(602,   69),
(602,   105),
(603,   13),
(603,   18),
(603,   31),
(603,   39),
(603,   39),
(603,   40),
(603,   46),
(603,   47),
(603,   48),
(603,   56)

select OpID,
       avg(ProcessMin) as ProcessMin
from
  (
    select OpID,
           ProcessMin,
           ntile(5) over(partition by OpID order by ProcessMin) as nt
    from @T
  ) as T
where nt <= 4
group by OpID

Enter Parameters

Options:
Switch sites:
loading Hold tight while we fetch your results