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

MySQL come riempire le ore/date mancanti nell'intervallo?

Non il più bello. Ma dovrebbe fare il trucco se davvero non puoi usare le tabelle temporanee:

select ifnull(count,0) as count,dh.hour_of_day,
dh.day_of_week,date_format((date('2012-01-02') + interval dh.day_of_week day),'%W') as name_of_day
from
(
select day_of_week,hour_of_day
from 
(
 select 0 as day_of_week union select 1 union select 2 union select 3 
 union select 4 union select 5 union select 6
) d
 join
(
 select 0 as hour_of_day 
 union select 1 union select 2 union select 3 union select 4 
 union select 5 union select 6 union select 7 union select 8
 union select 9 union select 10 union select 11 union select 12
 union select 13 union select 14 union select 15 union select 16
 union select 17 union select 18 union select 19 union select 20
 union select 21 union select 22 union select 23
) h
) dh
left outer join
(
SELECT
count(id) as count,
HOUR(created) as hour_of_day,
WEEKDAY(created) as day_of_week,
DATE_FORMAT(created,'%W') name_of_day
FROM visitors
GROUP BY day_of_week,hour_of_day
) v on dh.day_of_week = v.day_of_week and dh.hour_of_day = v.hour_of_day
ORDER BY dh.day_of_week,dh.hour_of_day ASC; 

Attenzione con questo però! Se esegui la query su più settimane, più giorni della settimana verranno sommati. Potresti prendere in considerazione l'aggiunta di un predicato "solo questa settimana". Ad esempio, aggiungi in where yearweek(created) = yearweek(now()) nella tua selezione originale per ottenere i dati solo per la settimana corrente.