也許這其中我比較分鐘日期對最大日起每ID每一個ID
select u.*
from t u
where u.id not in
(
select z.id
from
(
select s.*,t.id tid,t.mindt tmindt,t.maxdt tmaxdt
from
(
select id, min(dt) mindt,max(dt) maxdt
from t
group by id
order by id
) s
join
(select id, min(dt) mindt,max(dt) maxdt
from t
group by id
order by id
) t on
t.id <> s.id and
t.maxdt = s.mindt
) z
)
order by u.id,u.dt
鑑於此
truncate table t;
insert into t values
(1,'2017-01-01'),(1,'2017-01-02'),
(2,'2017-01-03'),(2,'2017-01-04'),
(3,'2017-01-04')
結果
+------+------------+
| id | dt |
+------+------------+
| 1 | 2017-01-01 |
| 1 | 2017-01-02 |
| 2 | 2017-01-03 |
| 2 | 2017-01-04 |
+------+------------+
4 rows in set (0.00 sec)
給這個
truncate table t;
insert into t values
(1,'2017-01-01'),(1,'2017-01-02'),
(2,'2017-01-03'),(2,'2017-01-04'),
(3,'2017-01-04'),
(4,'2017-01-04'),(4,'2017-01-06');
結果
+------+------------+
| id | dt |
+------+------------+
| 1 | 2017-01-01 |
| 1 | 2017-01-02 |
| 2 | 2017-01-03 |
| 2 | 2017-01-04 |
+------+------------+
4 rows in set (0.00 sec)
鑑於
truncate table t;
insert into t values
(1,'2017-01-01'),(1,'2017-01-02'),
(2,'2017-01-03'),(2,'2017-01-04'),
(3,'2017-01-04'),
(4,'2017-01-05'),(4,'2017-01-06');
結果
+------+------------+
| id | dt |
+------+------------+
| 1 | 2017-01-01 |
| 1 | 2017-01-02 |
| 2 | 2017-01-03 |
| 2 | 2017-01-04 |
| 4 | 2017-01-05 |
| 4 | 2017-01-06 |
+------+------------+
6 rows in set (0.02 sec)
爲什麼它不應該返回ID = 3時,它是你的裏面日期參數? – Matt
是的,返回3,但如果日期與其他日期交錯,可以過濾嗎? –
雖然邏輯是什麼?如果一個日期重疊,擺脫了最高重疊ID日期的所有ID? – Matt