【问题标题】:SQL: Query to get rows where the user was present for at least 1 day of a given month, yearSQL:查询以获取用户在给定月份、年份中至少存在 1 天的行
【发布时间】:2020-11-17 02:33:33
【问题描述】:

如何获取用户在 2019 年 3 月(2019 年 3 月 1 日至 31 日)至少存在 1 天的所有行。这 1 天可以是开始日期或结束日期,也可以是两者。


表格

| userid  | startdate | enddate |. postid
| ------- | --------- | ------  | -----
| u1 | 01-01-2019 | 03-05-2019. |  s1
| u1 | 03-06-2019 | 03-22-2019. |. s1
| u1 | 03-23-2019 | 05-20-2019. |  s3
| u2 | 03-01-2019 | 12-31-2099. |. s1
| u3 | 01-01-2019 | 04-20-2019. |  s2
| u4 | 01-04-2013 | 08-22-2020. |  s3
| u4 | 05-20-2020 | 12-31-2099. |  s3

预期结果:

| userid  | startdate | enddate |. postid
| ------- | --------- | ------  | -----
| u1 | 01-01-2019 | 03-05-2019. |  s1
| u1 | 03-06-2019 | 03-22-2019. |. s1
| u1 | 03-23-2019 | 05-20-2019. |  s3
| u2 | 03-01-2019 | 12-31-2099. |. s1
| u3 | 01-01-2019 | 04-20-2019. |  s2
| u4 | 01-04-2013 | 08-22-2020. |  s3

【问题讨论】:

    标签: mysql sql datetime where-clause


    【解决方案1】:

    您可以像这样检查存储期间与 2019 年 3 月之间的重叠:

    select t.*
    from mytable t
    where end_date >= '2019-03-01' and start_date <= '2019-03-31'
    

    【讨论】:

      猜你喜欢
      • 2014-11-21
      • 2017-12-04
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      相关资源
      最近更新 更多