[英]SQL query to group by largest date
I am trying to write an SQL query to do something like for each type, find the record with the largest date. 我正在尝试编写一个SQL查询以对每种类型执行类似的操作,以查找日期最大的记录。 My sample data:
我的样本数据:
date type
1505246220000 RNase P
1445652540000 Dye Plate 3
1505246940000 Dye Plate 1
1530529380000 ROI
1505246220000 ROI
1445651640000 ROI
1382579640000 ROI
1532830140000 Dye Plate 4
As you can see, for the type "ROI" it contains multiple rows. 如您所见,对于类型“ ROI”,它包含多行。 For that, I wanted to get the largest date.
为此,我想得到最大的约会。 My current SQL query is just simply selecting everything:
我当前的SQL查询只是简单地选择所有内容:
SELECT * FROM calibration_history ORDER BY calibration_date DESC
Any ideas? 有任何想法吗?
This is called aggregation. 这称为聚合。 You don't want to "group by largest date", but by type (ie you want one result row per type), for which you want the largest date each:
您不想“按最大日期分组”,而是要按类型(即每种类型希望一个结果行)进行分组,而每种类型都需要最大日期:
SELECT max(calibration_date), type
FROM calibration_history
GROUP BY type
ORDER BY max(calibration_date) DESC;
(I don't know if this is the order you want or if this was your attempt to get the largest dates. Of course you can ORDER BY type
instead for instance.) (我不知道这是您想要的订单还是这是您尝试获取最大日期的尝试。当然,您可以使用
ORDER BY type
代替。)
I would use correlated subquery
: 我会使用相关
subquery
:
select ch.*
from calibration_history ch
where calibration_date = (select max(ch1.calibration_date)
from calibration_history ch1
where ch1.type = ch.type
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.