我有下表(employee_organization):
| ID | 員工ID | 組織 ID | 開始日期 | 結束日期 |
|---|---|---|---|---|
| 1 | 77 | 16 | 2021-01-01 | 2021-06-30 |
| 2 | 11 | 23 | 2020-01-01 | 2021-05-27 |
| 3 | 77 | 16 | 2021-08-01 | 2021-08-31 |
| 4 | 77 | 16 | 2021-09-01 | 空值 |
我需要一個查詢,以篩選出記錄,其中employee_id = 77,organization_id = 16和end_date is null。如果未找到匹配的行,則回傳帶有max(end_date). 因此,在上面的示例表中,id=4應該只回傳行。
uj5u.com熱心網友回復:
SELECT *
FROM table
WHERE {needed conditions}
ORDER BY end_date IS NULL DESC, end_date DESC LIMIT 1
uj5u.com熱心網友回復:
一個通用的解決方案是使用相關子查詢來查找每個員工的最大日期(空值優先):
select *
from t
where end_date <=> (
select end_date
from t as x
where x.employee_id = t.employee_id
order by end_date IS NOT NULL, end_date desc
limit 1
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380091.html
