I have a loginAudit table and I am trying to get a count for all logins for each day. What I’d like to do is have days where there are no logins return their day and a login count of 0. Currently no row is returned for days with no logins.
Could be this isn’t possible and have to fill in empty groups in the app after query results returned?
SELECT DATEADD(day, DATEDIFF(day,0,LoginAudit.LoginDateTime), 0) as LoginDate,
COUNT(DISTINCT LoginAudit.LoginAuditID) AS Logins
FROM LoginAudit
GROUP BY DATEADD(day, DATEDIFF(day,0,LoginAudit.LoginDateTime), 0)
ORDER BY 1
Essentially what you’re asking is to join your table to a “table” of dates. The date table would have no gaps and you would group on the date value. So how to create a table of dates?
In SQL for Smarties, it’s suggested that you keep a table of integers around for cases when you need a gapless sequence to join to. Then you can select whatever sequence you need by joining your table to it.
So if you had an integer table with values going as many days back from NOW() as required you might do the following:
ETA, for mysql:
//create an integer table
if I need 0-99 consecutive numbers:
if I need consecutive dates: