mysql - 如何在 SQL 代码中不使用 groupby 来选择最大行数?
问题描述
我创建了一个 sql 代码,但问题是;
Column A Column B CreationDate
1 50 2019-10-10 10:41
1 80 2019-10-10 10:43
1 70 2019-10-10 11:05
2 60 2019-10-10 10:40
2 58 2019-10-10 10:41
2 50 2019-10-10 10:44
2 47 2019-10-10 11:00
通过排序,最后我想查看与最新创建日期相关的数据,例如:
Column A Column B CreationDate
1 50 2019-10-10 11:05
2 47 2019-10-10 11:00
因此我需要在 CreationDate 列中进行一些迭代,但我不知道如何在 sql 中进行。
我不能使用 groupby 因为 B 列阻止它这样做。此列是在 CreationDate 创建的预测列。因此,我只想获得最新的预测。
解决方案
好像你想要过滤。我会这样写:
select t.*
from t
where t.creation_date = (select max(t2.creation_date)
from t t2
where t2.a = t.a
);
如果你真的想避免聚合函数(虽然没有必要),这里有其他三种方法:
select t.*
from t
where t.creation_date = (select t2.creation_date
from t t2
where t2.a = t.a
order by t2.creation_date desc
limit 1
);
和:
select t.*
from t
where t.creation_date >= all (select t2.creation_date
from t t2
where t2.a = t.a
);
和:
select t.*
from t
where not exists (select 1
from t t2
where t2.creation_date > t.creation_date and
t2.a = t.a
);