So I have these two data tables, users and logins. There is a registration_date
column for users and a last_login
for logins. I am trying to find the average difference between the two columns from the two tables. What I believe to be the problem is that the registration_date
is just date while the last_login
is both date and time.
I first tried:
select avg(datediff(u.registration_date, l.last_login)) as avg_acttime from logins l
left join users u on l.userid = u.id and type like '%new%';
My result was null
.
So I then tried to convert the date and time last_login
column to just date.
select avg(datediff((DATE_FORMAT(u.registration_date,'%d-%m-%y')), (DATE_FORMAT(l.last_login,'%d-%m-%y')))) as avg_acttime from logins l
left join users u on l.userid = u.id and type like '%new%';
The result was again null
. I need some serious help getting the difference in days between this date column from one table and a date and time column from another table.
This is too long for a comment. First, I think you intend for users
to be the first table. Then, you don't need a left join
, because avg()
ignores NULL
values anyway. So a join
is sufficient:
select avg(datediff(u.registration_date, l.last_login)) as avg_acttime
from users u join
logins l
on l.userid = u.id and type like '%new%';
You would get NULL
values either because there are no rows generated by the from
clause or all the rows have a NULL
value for one of the columns. More specifically, I can think of the following possibilities:
logins
or users
has no rows. on
conditions. u.registration_date
and l.last_login
are always NULL
for each login. Having a datetime
and date
should not result in NULL
values.
Of these, my guess is that no rows match the on
condition. The type
comparison is the most likely cause of failure. Without sample data, it is hard to say more.
Your date format %d-%m-%y
will yield very strange results, if any at all. Change %d-%m-%y
to
%Y-%m-%d
Mind the capital Y
, or else mysql will format the date with 2 digits for year, what he will then confuse with the day.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.