id modid userid timemodified FROM_UNIXTIME(timemodified,'%d-%m-%Y')
410 32 46 1438971403 03-08-2015
411 32 46 1438971403 03-08-2015
412 66 977 1438971403 07-08-2015
412 66 977 1438971403 07-08-2015
413 67 34 1438971423 07-08-2015
414 68 16 1438971424 07-08-2015
415 132 23 1438972154 07-08-2015
416 134 2 1438972465 08-08-2015
417 115 2 1438996430 08-08-2015
418 130 977 1438996869 08-08-2015
我是根据今天的日期来计算过去4周前的框架而得到的。现在,我想分别向用户展示4周,如week1,week2,week3和week4,这可以是按列或按行的,这是最好的。
In detailed, from the above query, I need to separate data from week1 to week4,like
Week4 : No user
Week3 : 2 users (2,977)
Week2 : 4 users (16, 23, 34, 977)
Week1 : 1 user (46)
SET @unix_four_weeks_ago = UNIX_TIMESTAMP(curdate()) - 2419200;
SELECT *,FROM_UNIXTIME(timemodified,'%d-%m-%Y') FROM mod_users WHERE timemodified >= @unix_four_weeks_ago
最佳答案
我的猜测是您想根据timemodified
列划分每周的用户数。我会使用WEEK()
函数来做到这一点。
以下SQL将添加weeknumber
列以标识星期数:
SELECT WEEK(timemodified) weeknumber, dates.*
FROM dates
然后,如果要获取不同的用户数,则只需使用以下SQL:
SELECT WEEK(timemodified) weeknumber, COUNT(DISTINCT(userid)) users_count
FROM dates
GROUP BY weeknumber
您还可以添加
WHERE
子句以仅获得某些星期。因此,要从2015年8月23日开始的最后4周,我会这样做:SELECT WEEK(timemodified) weeknumber, COUNT(DISTINCT(userid)) users_count
FROM dates
WHERE WEEK(timemodified) <= WEEK('2015-08-23')
AND WEEK(timemodified) > (WEEK('2015-08-23') - 4)
GROUP BY weeknumber
希望我假设正确。 :-)
关于mysql - 如何在MySQL中每周对数据进行分组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32146614/