First of all: sorry for the title, but maybe I will find a better one later.
I asked this some minutes ago, but since I was not able to describe what I want I try it
Example table:
CREATE TABLE `test`.`user_login_history` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`userid` INTEGER UNSIGNED NOT NULL,
`date` DATETIME NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB;
Once a user login, check whether he/she has login today or not:
select count(*) from user_login_history where
userid = 1 and `date` = '2013-01-28 00:00:00';
If the returned value is 1, means he/she has login today. no changes needed.
but, if the returned value is 0, means he/she has not login today. So record it down.
insert into user_login_history(userid,`date`)values(1,'2013-01-28 00:00:00');
Q1. How many users were online TODAY that were also online YESTERDAY?
select count(*) from user_login_history u where
u.`date` = '2013-01-28 00:00:00' and
(
select count(*) from user_login_history v where
v.`date` = '2013-01-27 00:00:00' and
v.userid = u.userid
) = 1;
Q2. How many users were online TODAY that were also online within in the last TWO DAYS
select count(*) from user_login_history u where
u.`date` = '2013-01-28 00:00:00' and
(
select count(*) from user_login_history v where
v.`date` >= '2013-01-26 00:00:00' and
v.`date` <= '2013-01-27 00:00:00' and
v.userid = u.userid
) > 0;
Q3. How many users were online TODAY that were also online within the last 7 DAYS
select count(*) from user_login_history u where
u.`date` = '2013-01-28 00:00:00' and
(
select count(*) from user_login_history v where
v.`date` >= '2013-01-21 00:00:00' and
v.`date` <= '2013-01-27 00:00:00' and
v.userid = u.userid
) > 0;