简体   繁体   English

返回按周分组的行数 MySQL

[英]Return the count of rows grouped by week MySQL

I am trying to get the row count from a MySQL table where the data is grouped by WEEK.我试图从数据按周分组的 MySQL 表中获取行数。

So far the query I have is:到目前为止,我的查询是:

 "SELECT count(*) as tweets, twitTimeExtracted as date 
  FROM scene.twitData 
  group by week(twitTimeExtracted)"

This query returns the data below:此查询返回以下数据:

在此处输入图片说明

As you can see, the weeks are not correct, I'm expecting data for each week starting with Monday 7th January (7,14,21,28,4,11 etc...) and running through to this week.如您所见,周数不正确,我期待从 1 月 7 日星期一(7、14、21、28、4、11 等)开始到本周的每周数据。

I also tried a modified version of the orignal query:我还尝试了原始查询的修改版本:

SELECT count(*) as tweets, twitTimeExtracted as date 
FROM scene.twitData 
WHERE date(twitTimeExtracted) 
   BETWEEN '2013-01-07' and '2013-03-11' 
group by week(twitTimeExtracted)

This returns similar results as the first query.这将返回与第一个查询类似的结果。

Maybe there is an inconsistency with some data stored in the DATETIME: twitTimeExtracted column on a few rows of data?也许在几行数据上存储在 DATETIME: twitTimeExtracted 列中的某些数据存在不一致? I don't really know I'm not very experienced with MySQL.我真的不知道我对 MySQL 不是很有经验。

Any help would really be appreciated.任何帮助将不胜感激。

Thanks谢谢

This converts the datetime value to the appropriate Monday of the week这会将datetime值转换为一周中适当的星期一

select count(*) as tweets,
       str_to_date(concat(yearweek(twitTimeExtracted), ' monday'), '%X%V %W') as `date`
from twitData 
group by yearweek(twitTimeExtracted)

yearweek returns both week and year. yearweek返回周和年。 Together with the string monday , str_to_date gives you the Monday's datetime value. str_to_date与字符串monday str_to_date为您提供星期一的datetime值。

If your week starts on Monday , use yearweek(twitTimeExtracted, 1) instead.如果您的一周从Monday开始,请改用yearweek(twitTimeExtracted, 1)

One option to always get the Monday of the week is to use adddate:始终获取一周中的星期一的一种选择是使用 adddate:

SELECT count(*) as tweets, adddate(twitTimeExtracted, INTERVAL 2-DAYOFWEEK(twitTimeExtracted) DAY)
FROM twitData 
WHERE date(twitTimeExtracted) 
   BETWEEN '2013-01-07' and '2013-03-11' 
GROUP BY adddate(twitTimeExtracted, INTERVAL 2-DAYOFWEEK(twitTimeExtracted) DAY)

SQL Fiddle Demo SQL 小提琴演示

try this:试试这个:

 SELECT count(*) as tweets, 
     date_add('7 Jan 2012', day, datediff('7 Jan 2012', twitTimeExtracted)) % 7   
 FROM scene.twitData 
 group by date_add('7 Jan 2012', day, datediff('7 Jan 2012', twitTimeExtracted)) % 7

An alternate solution:替代解决方案:

SELECT DATE(DATE_SUB(yourDate, INTERVAL WEEKDAY(yourDate) DAY));

Eg:例如:

SELECT DATE(DATE_SUB(DATE("2016-04-11"), INTERVAL WEEKDAY(DATE("2016-04-11")) DAY));

You can also try this.你也可以试试这个。

select 
DATE_ADD(DATE(date), INTERVAL (7 - DAYOFWEEK(date)) DAY) as weekend,
count(tweets)
from scene.twitData 
  group by weekend;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM