I got 2 columns, 'create_time' is when the account has been registered and 'last_play' is when the account has logged in the last time. I want to select accounts which have been registered in a specific week / month and have been active within the last 2 days of this specific week / month.
Here is how I select ALL entries of last week without considering last_play (works):
SELECT COUNT(id) FROM account.account
WHERE WEEKOFYEAR(create_time) = WEEKOFYEAR(NOW()) - 1
AND YEAR(create_time) = YEAR(NOW());
That's my current query for last week which doesn't work:
SELECT COUNT(id) FROM account.account
WHERE WEEKOFYEAR(create_time) = WEEKOFYEAR(NOW()) - 1
AND YEAR(create_time) = YEAR(NOW())
AND DATE(last_play) BETWEEN
ADDDATE(DATE(DATE_SUB(NOW(), INTERVAL 1 WEEK)),
INTERVAL 1 - DAYOFWEEK(DATE(NOW())) DAY)
AND DATE(NOW());
Basing on your first working query, you can use the MySQL function WEEKDAY
to identify saturdays and sundays:
SELECT COUNT(id) FROM account.account
WHERE WEEKOFYEAR(create_time) = WEEKOFYEAR(NOW()) - 1
AND YEAR(create_time) = YEAR(NOW())
AND WEEKOFYEAR(last_play) = WEEKOFYEAR(create_time) //last_play is in the same week as create_time
AND WEEKDAY(last_play) IN (5,6); //wekkday is saturday or sunday
This gives you entries which were active on the saturday or sunday in the same week they registered.
EDIT: For months, you basically do the same thing, but replace WEEKOFYEAR
by MONTH
and WEEKDAY
by DAYOFMONTH
. The last two days of a given month you can find manually by checing for all possible cases:
SELECT COUNT(id) FROM account.account
WHERE MONTH(create_time) = MONTH(NOW()) - 1
AND YEAR(create_time) = YEAR(NOW())
AND MONTH(last_play) = MONTH(create_time) //last_play is in the same MONTH as create_time
AND
(DAYOFMONTH(last_play) IN (30,31) AND MONTH(last_play) IN (1,3,5,7,8,10,12)
OR DAYOFMONTH(last_play) IN (29,30) AND MONTH(last_play) IN (4,6,9,11)
OR DAYOFMONTH(last_play) IN (27,28) AND MONTH(last_play) IN (2))
Never mind a leap year ;-). Or incorporate it again manually by yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With