【问题标题】:Records added since specific month this year in SQL自今年特定月份以来在 SQL 中添加的记录
【发布时间】:2020-10-01 15:25:08
【问题描述】:

我有一个包含以下数据的表

userId | name   |   from       
1      | aaa    |  2020-09-23  
2      | bbb    |  2020-09-01  
3      | ccc    |  2019-05-12  
4      | ddd    |  2019-06-01  
5      | eee    |  2018-06-23  
6      | fff    |  2018-07-23  

这是为了教育目的,因此一年从 9 月到 8 月,而不是从 1 月到 12 月。如何输出自去年 9 月以来添加的所有用户(如果是 2020 年 10 月,那么 1 个月前,如果是 2021 年 1 月,那么 4 个月前)?查询必须是相对的,以便它始终输出上一个 9 月到运行查询的时间,而不是特定的 9 月。

查询的结果应该是

bbb 2020-09-01 
aaa 2020-09-23  

【问题讨论】:

  • 样本数据很棒,但也不要忘记向我们展示预期的结果。
  • 谢谢,我已经添加了这个

标签: mysql sql


【解决方案1】:

不存在:

select t.* from tablename t
where t.`from` >= concat(year(current_date), '-09-01') 
and not exists (
  select 1 from tablename
  where name = t.name
    and `from` between 
               concat(year(current_date), '-09-01') - interval 1 year 
               and 
               concat(year(current_date), '-09-01') - interval 1 day
)

或许:

select t.* from tablename t
where t.`from` >= concat(year(current_date) - (month(current_date) < 9), '-09-01') 
and not exists (
  select 1 from tablename
  where name = t.name
    and `from` between 
               concat(year(current_date) - (month(current_date) < 9), '-09-01') - interval 1 year 
               and 
               concat(year(current_date) - (month(current_date) < 9), '-09-01') - interval 1 day
)

因此,如果您在 2021 年 3 月执行查询,您将获得将当前教育年度与上一教育年度进行比较的正确结果。

请参阅demo
结果:

> userId | name | from      
> -----: | :--- | :---------
>      1 | aaa  | 2020-09-23
>      2 | bbb  | 2020-09-01

【讨论】:

  • 但是由于您对这些日期进行了硬编码,如果查询在明年运行,数据将如何更改为仅包括从 2021 年 9 月开始添加的用户?
  • @JeremyRenner2 检查我的第二个查询。
【解决方案2】:

您可以减去 9 个月并与年份进行比较:

where year(`from` - interval 9 month) = year(curdate() - interval 9 month)

实际上,您可能需要year(curdate()) +/- 1,具体取决于您如何识别年份。

【讨论】:

  • 谢谢,但是我如何使 9 相对于我们今年的位置?例如,如果我现在运行该查询,它不会返回 9 月的任何内容,因为它只是 1 个月前
  • @JeremyRenner2 。 . .您也可以从当前日期减去 9 个月。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
相关资源
最近更新 更多