Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Select entries from last 2 days of specific week / month

Tags:

date

sql

php

mysql

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());
like image 964
Marius Avatar asked Nov 01 '22 21:11

Marius


1 Answers

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.

like image 131
davidhigh Avatar answered Nov 09 '22 15:11

davidhigh