简体   繁体   English

SQL查询两周之间获取数据?

[英]SQL Query to get data between two weeks?

I have a week column with week numbers as w0, w1, w2... . 我有一个星期列,星期数为w0, w1, w2... I am trying to get last last six weeks data. 我正在尝试获取最近六周的数据。 Here's the sql query I am using. 这是我正在使用的SQL查询。

SELECT * FROM week 
WHERE uid = '9df984da-4318-1035-9589-493e89385fad'       
  AND report_week BETWEEN `'w52' AND 'w5'`;

'w52' is essentially week 52 in December 2015 and 'w5' is Jan 2016. The 'between' seems to not work. 'w52'实际上是2015年12月的第52周, 'w5'是2016年1月。 'between'似乎不起作用。 Whats the best way to get data from the above two weeks? 从上述两周中获取数据的最佳方法是什么?

Here's the CREATE TABLE statement: 这是CREATE TABLE语句:

CREATE TABLE `week` (`uid` VARCHAR(255) DEFAULT '' NOT NULL,
                     `report_week` VARCHAR(7) NOT NULL,
                     `report_files_active` BIGINT DEFAULT NULL);

Essentially this table is getting populated from other table which has date column. 本质上,该表是从具有日期列的其他表中填充的。 It uses dates from other table and summarizes weekly data into this. 它使用其他表格中的日期,并将每周数据汇总到其中。

Any help is appreciated. 任何帮助表示赞赏。

Refer to this SO Discussion which details the reasons for a problem similar to yours. 请参阅此SO讨论 ,其中详细说明了与您类似的问题的原因。

BETWEEN 'a' and 'b' actually matches to columnValue >='a' and columnValue <= 'b' BETWEEN 'a' and 'b'实际匹配columnValue >='a' and columnValue <= 'b'

In your case w52 is greater than w5 due to lexicographic ordering of Strings - this means that the BETWEEN clause will never return a true (think about it as equivalent to saying BETWEEN 10 and 1 instead of BETWEEN 1 and 10 . 在你的情况W52比大于W5由于字符串的字典序-这意味着BETWEEN子句将不会返回一个真正的(想想它相当于说BETWEEN 10 and 1 ,而不是BETWEEN 1 and 10

Edit to my response: 编辑我的回复:

Refrain from storing the week value as a string. 不要将星期值存储为字符串。 Instead here are a couple of approaches in order of their preference: 相反,这里有一些按优先顺序排列的方法:

  1. Have a timestamp column. 有一个时间戳列。 You can easily then use MySQL query facilities to extract the week information out of this. 然后,您可以轻松地使用MySQL查询工具从中提取星期信息。 For a reference see this post. 有关参考,请参阅帖子。
  2. Maintain two columns - YEAR, WEEKNO where YEAR will store values like 2015, 2016 etc and WEEKNO will store the week number. 维护两列YEAR, WEEKNO ,其中YEAR将存储诸如WEEKNO等的值WEEKNO将存储星期数。 This way you can query data for any week in any year. 这样,您可以查询一年中任何一周的数据。

请向我显示表结构和数据库名称,因为它与其他表有所不同,如果是任何时间戳,则可以使用'systemdate' AND 'systemdate-6'

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

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