假设您想为每个电话获取具有最大 id 的行,请使用:
select
t.*
from vici t
inner join (
select tel, max(id) id
from vici
group by tel
) t2 on t.tel = t2.tel
and t.id = t2.id;
编辑 1:
如果它基于 dateippo,只需将 id 替换为 dateippo,如下所示:
select
t.*
from vici t
inner join (
select tel, max(dateippo) dateippo
from vici
group by tel
) t2 on t.tel = t2.tel
and t.dateippo = t2.dateippo;
编辑 2:
首先按状态 = 'ok' 排序,然后按日期排序,
select
t.*
from vici t
inner join (
select tel, max(id) id
from vici
group by tel
) t2 on t.tel = t2.tel
and t.id = t2.id
order by t.status <> 'ok', t.dateippo;
编辑 3:
select
t.*
from vici t
inner join (
select
tel,
case when count(status = 'ok') > 1 then
max(case when status = 'ok' then dateippo end)
else max(dateippo) end dateippo
from vici
group by tel
) t2 on t.tel = t2.tel
and t.dateippo = t2.dateippo;
select * from vici;
或基于id:
select
t.*
from vici t
inner join (
select
tel,
case when count(status = 'ok') > 1 then
max(case when status = 'ok' then id end)
else max(id) end id
from vici
group by tel
) t2 on t.tel = t2.tel
and t.id = t2.id;
select * from vici;
+------+-------------+------------+--------+---------+
| id | tel | dateippo | status | lead_id |
+------+-------------+------------+--------+---------+
| 1 | 11111111111 | 2017-01-02 | ok | 4 |
| 4 | 22222222222 | 2017-01-10 | ok | 7 |
+------+-------------+------------+--------+---------+
2 rows in set (0.00 sec)