我有下表tbl_crps,请注意,列[[crp多次出现,但是id和starts_on在具有相同 crp。
id | crp | starts_on |
------------------
1 | 20 | 2020-02-09 |
2 | 31 | 2019-06-05 |
3 | 20 | 2018-01-10 |
4 | 31 | 2021-07-03 |
5 | 58 | 2022-01-01 |
6 | 58 | 2025-02-02 |
我需要在以下情况下提取记录:,则存在一个或多个具有过去starts_on的记录,那么在那些具有crp的记录(具有过去日期的记录)中,具有最大id的记录必须是返回
- 如果是
crp
crp
SELECT * FROM tbl_crps
AND id IN (SELECT MAX(b.id) FROM tbl_crps b WHERE b.starts_on <= "2020-10-02")
将返回ID为3和2的记录。
我需要实现的是将结果[ crp
有可能吗?也许是这样吗?
SELECT * FROM tbl_crps a
WHERE id IN (
SELECT MAX(a.id) FROM tbl_crps a WHERE a.starts_on <= "2020-10-02"
)
UNION
(
SELECT * FROM tbl_crps b
WHERE id IN (
SELECT MAX(c.id) FROM tbl_crps c WHERE c.starts_on > "2020-10-02"
AND c.crp NOT IN (
SELECT d.crp FROM tbl_crps d
WHERE id IN (
SELECT MAX(e.id) FROM tbl_crps e WHERE e.starts_on <= "2020-10-02")
)
)
)
我有下表tbl_crps,请注意,列crp出现了不止一次,但id和starts_on在具有相同crp的记录中将始终不同。 id | crp | starts_on | ----------------...id crp starts_on
2 31 2019-06-05
3 20 2018-01-10
5 58 2022-01-01
6 58 2025-02-02
根据我对要求的理解,这似乎是正确的。简而言之
1 - NOT included because its date is in the past ('current' date = 2020-10-02)
and its ID is NOT the greatest among records in the past with that CRP.
2 - included because its date is in the past and its ID is the greatest
among records with that CRP which have dates in the past.
3 - date is in the past, ID is greatest for that CRP with date in the past
4 - NOT included because date is in the future, but CRP is included in recs
from first subquery.
5 - date is in the future, and CRP does not occur in first subquery
6 - date is in the future, and CRP does not occur in first subquery
db<>fiddle here