【问题标题】:Get variable MIN Date based on marker in row根据行中的标记获取变量 MIN Date
【发布时间】:2020-07-09 14:43:59
【问题描述】:

我正在使用MySQLphpMyAdmin, 下面是我的数据表:

+--------+---------+-----------------+
| userID | context |      time       |
+--------+---------+-----------------+
|    111 |         | 7/1/2021        |
|    111 |         | 7/16/2019       |
|    111 | Reset   | 7/15/2019       |
|    222 |         | 7/9/2020        |
|    222 | Reset   | 7/8/2020        |
|    333 | Reset   | 5/11/2020       |
|    333 |         | 5/10/2020       |
|    444 |         | 9/8/2020        |
+--------+---------+-----------------+

我正在寻找一个SELECT 查询,它给我的MIN 时间大于或等于在context 列中记录重置 的日期。如果context 列中不存在 Reset 标记,我希望包含结果。

所以对于上表,我期待结果:

+--------+-----------------+
| userID |      time       |
+--------+-----------------+
|    111 | 7/15/2019       |
|    222 | 7/8/2020        |
|    333 | 5/11/2020       |
|    444 | 9/8/2020        |
+--------+-----------------+

我试过了:

SELECT * FROM foo as a 
WHERE ((SELECT MIN(a.time) FROM foo) >= (SELECT Max(a.time) FROM foo where context = 'Reset')) group by userID

不会产生我预期的输出,但会返回:

+--------+-----------+
| userID |   time    |
+--------+-----------+
|    111 | 7/1/2021  |  <--- wrong 
|    222 | 7/8/2020  |
|    333 | 5/11/2020 |
+--------+-----------+

【问题讨论】:

  • 您使用的是哪个 dbms?
  • 我正在使用 MySQL 和 PhpMyAdmin,并通过 gping 使用此信息编辑我的问题
  • 指定的预期结果是“等于重置的日期”行。 “更大或”不会添加任何行吗?
  • 你想要每个用户标识一行吗?
  • 将行 (444,'9/8/2020') 添加到样本数据中,并根据需要调整指定的结果。

标签: mysql sql subquery


【解决方案1】:

使用窗口函数:

select t.*,
       coalesce(next_time, time) as imputed_time
from (select t.*,
             sum(context = 'reset') over (partition by user_id) as cnt_reset,
             min(case when context is null then time end) over (partition by userid order by time rows between current row and unbounded following) as next_time
      from t
     ) t
where cnt_reset = 0 or context = 'reset';

【讨论】:

    【解决方案2】:

    根据您的预期结果,您可以尝试以下查询-

    SELECT userID, MAX(time)
      FROM YOUR_TABLE
     WHERE context = 'RESET'
     GROUP BY userID
     UNION ALL
    SELECT userID, MAX(time)
      FROM YOUR_TABLE
     WHERE context IS NULL
     GROUP BY userID
     ORDER BY userID
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-18
      • 2020-07-17
      • 2022-07-16
      • 2021-11-27
      • 2019-06-25
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      相关资源
      最近更新 更多