Mysql
 sql >> Database >  >> RDS >> Mysql

Come ottenere min max e avg dalla tabella in mysql con righe diverse?

Se vuoi i valori in una singola riga, puoi farlo:

select max(playtime), min(playtime), avg(playtime)
from yourtable
group by mediaid;

Se li vuoi in righe separate, usa un 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;

vedi SQL Fiddle con demo

Modifica n. 1, utilizzando i dati di esempio aggiunti:

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

Vedi SQL Fiddle con demo