gpt4 book ai didi

Mysql查询根据两种逻辑过滤掉数据

转载 作者:可可西里 更新时间:2023-11-01 06:45:30 25 4
gpt4 key购买 nike

这是一个示例表:

  sample_id  |      timestamp       | p_id
============================================
62054 | 2018-09-25 10:18:15 | 2652
62054 | 2018-09-27 16:44:57 | 966
62046 | null | 1809
62046 | 2018-09-25 10:18:15 | 2097

我们需要过滤掉唯一的sample_id列,但是逻辑是

  1. 如果时间戳列为空,则返回那些空列数据

        62046 | null | 1809
  2. 如果时间戳列不为空,则返回最新的时间戳列数据

     62054 | 2018-09-27 16:44:57 | 966

如果有人提供 sql 查询,那就太好了。

我们需要这样的东西,

WHERE
IF(
NOT NULL = all row group by sample_id,
row where cancelled_at is maximum,
null column
)

最佳答案

此查询应该会为您提供所需的结果。它查找具有 NULL 时间戳的行,或具有 non-NULL 时间戳的行,这是该 sample_id 的最大时间戳,但前提是没有该 sample_id 的一行具有 NULL 时间戳:

SELECT *
FROM table1 t1
WHERE timestamp IS NULL OR
timestamp = (SELECT MAX(timestamp)
FROM table1 t2
WHERE t2.sample_id = t1.sample_id) AND
NOT EXISTS (SELECT *
FROM table1 t3
WHERE t3.sample_id = t1.sample_id AND
t3.timestamp IS NULL)

输出:

sample_id   timestamp               p_id
62054 2018-09-27T16:44:57Z 966
62046 (null) 1809

关于Mysql查询根据两种逻辑过滤掉数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52575117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com