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

MySQL como preencher horas/datas ausentes no intervalo?


Não é o mais bonito. Mas deve funcionar se você realmente não puder usar tabelas temporárias:
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; 

Mas cuidado com isso! Se você executar a consulta em várias semanas, vários dias da semana serão adicionados. Você pode considerar adicionar um predicado 'somente esta semana'. Por exemplo, adicione where yearweek(created) = yearweek(now()) em sua seleção original para obter dados apenas para a semana atual.