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

MySQL viser tæller på 0 for datoer uden registreringer

Ok fra mit tidligere svar fra tråden MySql Single Table, vælg de sidste 7 dage og inkluder tomme rækker

Her er hvad du kan gøre for at gøre datovalget dynamisk

select 
t1.attempt_date,
coalesce(SUM(t1.attempt_count+t2.attempt_count), 0) AS attempt_count
from
(
  select DATE_FORMAT(a.Date,'%Y/%m/%d') as attempt_date,
  '0' as  attempt_count
  from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
  ) a
  where a.Date BETWEEN NOW() - INTERVAL 7 DAY AND NOW()
)t1
left join
(
  SELECT DATE_FORMAT(attempt_date,'%Y/%m/%d') AS attempt_date, 
  COUNT(*) AS attempt_count
  FROM users_attempts
  WHERE DATE_SUB(attempt_date, INTERVAL 1 DAY) > DATE_SUB(DATE(NOW()), INTERVAL 1 WEEK) 
  GROUP BY DAY(attempt_date) DESC
)t2
on t2.attempt_date = t1.attempt_date
group by DAY(t1.attempt_date)
order by t1.attempt_date desc;

DEMO



  1. Docker-maskine på Mac:Kan du ikke se monterede volumener på docker-vært/docker-maskine? Hvor opbevares mængder fysisk?

  2. Uventet undtagelse:SQLSTATE[HY000] [1045] Adgang nægtet for bruger ****@'localhost' (bruger adgangskode:JA)

  3. Opdeling af streng i flere rækker i Oracle

  4. php artisan migrate throwing [PDO-undtagelse] Kunne ikke finde driveren - bruger Laravel