我正在尝试编写一个SQL查询以对每种类型执行类似的操作,查找日期最大的记录。我的样本数据:
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
如您所见,对于“ ROI”类型,它包含多行。为此,我想得到最大的约会。我当前的SQL查询只是简单地选择所有内容:
SELECT * FROM calibration_history ORDER BY calibration_date DESC
有什么想法吗?
答案 0 :(得分:1)
这称为聚合。您不想“按最大日期分组”,而是要按类型(即,每种类型只需要一个结果行),而每个类型都需要最大日期:
SELECT max(calibration_date), type
FROM calibration_history
GROUP BY type
ORDER BY max(calibration_date) DESC;
(我不知道这是您想要的订单还是这是您尝试获取最大日期的尝试。例如,您当然可以ORDER BY type
来代替。)
答案 1 :(得分:0)
我会使用 correlated subquery
:
select ch.*
from calibration_history ch
where calibration_date = (select max(ch1.calibration_date)
from calibration_history ch1
where ch1.type = ch.type
);