简体   繁体   English

获取上周从(周一到周日)的数据

[英]Get the data of the last week from (Monday to Sunday)

I would like to get the data from the last week.我想获取上周的数据。 A week is Monday to Sunday.一周是周一到周日。

I made this query:我做了这个查询:

    sql = 'SELECT COUNT(*) ' \
          'FROM panelname ' \
          'WHERE year(date) = year(now()) ' \
          'AND date BETWEEN date_sub(now(),INTERVAL 1 WEEK) AND now() '
    cursor.execute(sql)
    test = cursor.fetchall()
    print(test)

The problem with AND date BETWEEN date_sub(now(),INTERVAL 1 WEEK) AND now() is that it takes the data from the past 7 days. AND date BETWEEN date_sub(now(),INTERVAL 1 WEEK) AND now()的问题在于它需要过去 7 天的数据。 If I am Tuesday of the current week and I run it, I will get the data from last week's Tuesday up until this week's Tuesday, which is not what I want.如果我是本周的星期二并运行它,我会得到上周星期二到本周星期二的数据,这不是我想要的。 It should give the data from last Monday down to last Sunday.它应该给出从上周一到上周日的数据。

I also precise that it should not use the DATEADD function, because I don't have the admin rights to use it.我还指出它不应该使用 DATEADD function,因为我没有使用它的管理员权限。

For example : I run the query today, it doesn't matter which day we are, and I get the last week of data (Monday to Sunday).例如:我今天运行查询,我们在哪一天都没有关系,我得到了最后一周的数据(周一到周日)。

Thank you.谢谢你。

You must first get the most recent Monday and use it as a reference point to calculate the 5 previous weeks:您必须首先获取最近的星期一并将其用作参考点来计算前 5 周:

SELECT COUNT(*)
FROM panelname
WHERE date >= CURDATE() - INTERVAL WEEKDAY(CURDATE()) day - INTERVAL 5 week
AND date < CURDATE() - INTERVAL WEEKDAY(CURDATE()) day

UPDATE更新

To get the aggregated count per each week you need to group by week:要获得每周的汇总计数,您需要按周分组:

SELECT WEEKOFYEAR(date),COUNT(*)
FROM panelname
WHERE date >= CURDATE() - INTERVAL WEEKDAY(CURDATE()) day - INTERVAL 5 week
AND date < CURDATE() - INTERVAL WEEKDAY(CURDATE()) day
GROUP BY WEEKOFYEAR(date)

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

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