Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Como obter min max e avg da tabela no mysql com linhas diferentes?


Se você quiser os valores em uma única linha, você pode fazer isso:
select max(playtime), min(playtime), avg(playtime)
from yourtable
group by mediaid;

Se você os quiser em linhas separadas, use um UNION ALL :
select max(playtime) playtime, mediaid, 'Max' Type
from yourtable
group by mediaid
union all
select min(playtime) playtime, mediaid, 'Min'
from yourtable
group by mediaid
union all
select avg(playtime) playtime, mediaid, 'Avg'
from yourtable
group by mediaid
order by mediaid, playtime;

consulte SQL Fiddle with Demo


Edite #1, usando seus dados de amostra adicionados:
select m.medTitle, 
  min(TIMESTAMPDIFF(SECOND, s.dmtViewStart, s.dmtViewEnd)) playtime
from tbldoctormediatracktest s
left join tblmedia m
  on s.MedId = m.MedId
group by m.medTitle
union all

select m.medTitle, 
  avg(TIMESTAMPDIFF(SECOND, s.dmtViewStart, s.dmtViewEnd)) playtime
from tbldoctormediatracktest s
left join tblmedia m
  on s.MedId = m.MedId
group by m.medTitle
union all

select m.medTitle, 
  max(TIMESTAMPDIFF(SECOND, s.dmtViewStart, s.dmtViewEnd)) playtime
from tbldoctormediatracktest s
left join tblmedia m
  on s.MedId = m.MedId
group by m.medTitle
order by medTitle,  playtime

Veja SQL Fiddle with Demo