![](/img/trans.png)
[英]show the latest date, not a random one, after group by in SELECT statement (MySQL)
[英]Mysql, How to group by columns and select latest date?
您可以按如下方式使用NOT EXISTS
:
SELECT *
FROM employment_informations t1
WHERE NOT EXISTS
(SELECT 1 FROM employment_informations t2
WHERE t1.employee_id = t2.employee_id
AND t1.field_name = t2.field_name
AND t2.created_at > t1.created_at)
對於那些想要 select 列的人,這些列不屬於 group by 或不是聚合 function 我是這樣做的:
SELECT *
FROM employment_informations t1
WHERE (t1.employee_id, t1.field_name, t1.created_at) = ANY(
SELECT
t2.employee_id,
t2.field_name,
MAX(t2.created_at)
FROM employment_informations t2
WHERE t2.effectivity_date = '2021-01-20'
GROUP BY t2.employee_id, t2.field_name
)
ORDER BY t1.employee_id, t1.field_name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.