用户 | 时间戳 |
---|---|
1 | 2021-2-10 | 已回答
1 | 2021-15 | 已回答
2 | 2021-2-11 | 已回答
2 | 2021-2-14 | 已回答
2 | 2021-12 | 未回答[/tr>
3 | 2021-2-16 | 下一个问题[/tr>
3 | 2021-13 | 下一个问题//tr>
4 | 2021-12 | 下一个问题[/tr>
4 | 2021-2-17 | 已回答
您可以考虑
查询1。使用窗口函数(如ROW_NUMBER
)对行进行排序和筛选
Query 2。使用找到最早开始日期的聚合查询筛选您的记录
请参阅下面的一种方法来完成上面建议的方法。
查询#1
SELECT
user,
timestamp,
event
FROM (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY user ORDER BY timestamp) rn
FROM
my_table
) t
WHERE
rn=1;
用户 | 时间戳 | 事件|
---|---|---|
1 | 2021-02-10 | 已回答|
2021-02-11 | 已回答 | |
3 | 2021-02-13 | 下一个问题[/tr>|
4 | 2021-02-12 | 下一个问题 |
- 首先,您将根据时间戳和id为每一行创建排名
- 然后我们只选择秩=1
WITH data as (
SELECT
*,
ROW_NUMBER () OVER(PARTITION BY USER ORDER BY TIMESTAMP) as rank_
FROM my_table
)
SELECT * from data where rank_ = 1
这应该适用于MySQL 5.6:
select * from (
select * from events
order by user, timestamp
) a
group by user
having timestamp = min(timestamp);
编辑
MySQL 8.0版本:
select e1.user, e1.timestamp, event from (
select user, min(timestamp) timestamp
from events
group by user
) e1
left join (select * from events) e2
on e2.user = e1.user
and e2.timestamp = e1.timestamp
DB Fiddle