基于最小时间MYSQL获取不同的数据[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我这里有一个示例数据:

enter image description here

这是我想要的输出:

enter image description here

如何根据最短时间获得明确的价值?

这是我试过的更新

enter image description here

mysql sql greatest-n-per-group
2个回答
0
投票

用于过滤的相关子查询可能是最简单的解决方案:

select t.*
from t
where t.timestamp = (select min(t2.timestamp)
                     from t t2
                     where t2.id = t.id
                    );

如果您想要最早的记录,您可能需要考虑日期:

select t.*
from t
where (t.date, t.time) in (select t2.date, t2.time
                           from t t2
                           where t2.id = t.id
                           order by t2.date desc, t2.time desc
                          );

或者如果您想要每个日期的最早记录:

select t.*
from t
where t.timestamp = (select min(t2.timestamp)
                     from t t2
                     where t2.id = t.id and
                           t2.date = t.date
                    );

0
投票

使用MySQL 8.0,窗口函数通常是最有效的方法:

SELECT col1, col2, col3, col4, col5
FROM (
    SELECT t.*, ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col4) rn
    FROM mytable t
) x WHERE rn = 1

对于早期版本,我会使用带有相关子查询的NOT EXISTS条件:

SELECT *
FROM mytable t
WHERE NOT EXISTS (
    SELECT 1 FROM mytable t1 WHERE t1.col2 = t.col2 AND t1.col4 < t.col4 
)

Demo on DB Fiddle

| col1 | col2 | col3       | col4     | col5       |
| ---- | ---- | ---------- | -------- | ---------- |
| 2    | AAA  | Customer 1 | 07:00:00 | 2019-03-04 |
| 3    | BBB  | Customer 2 | 15:00:00 | 2019-03-04 |

为了有效地执行此操作,您需要mytable(col2, col4)上的索引:

CREATE INDEX mytable_idx ON mytable(col2, col4);

如果您有多个具有相同col1col2的记录,则可以使用列c1添加其他条件以避免结果集中的重复,我理解这是表的主键:

SELECT *
FROM mytable t
WHERE NOT EXISTS (
    SELECT 1 
    FROM mytable t1 
    WHERE 
        t1.col2 = t.col2 
       AND (
           t1.col4 < t.col4 
           OR (t1.col4 = t.col4 AND t1.col1 < t.col1)
       )
)

Updated DB Fiddle

© www.soinside.com 2019 - 2024. All rights reserved.