Mysql 检测 doublon 并按日期排序

标签 mysql group-by duplicates

我对此请求有疑问: SELECT COUNT() AS nbr_doublon, tel, dateippo FROM vici GROUP BY tel HAVING COUNT() > 1

enter image description here

我想获得这个结果:

enter image description here

^结果只会有尝试过的日期的重复项 请帮忙

------------------------表格数据

id  tel            dateippo     status  lead_id 
1   11111111111     2017-01-02  ok      4   y
2   11111111111     2017-01-26  na      5   y
3   11111111111     2017-01-28  rep     4   n
4   22222222222     2017-01-10  ok      7   y

我想要的结果:

id  tel             dateippo    status  lead_id 
1   11111111111     2017-01-02  ok      4   
4   22222222222     2017-01-10  ok      7   

首先测试状态是否等于“ok”并按 dateippo 订购 否则按 dateippo 订购

感谢帮助

最佳答案

假设您想要获取每个电话的最大 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)

关于Mysql 检测 doublon 并按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41879180/

相关文章:

mysql - 引用另一个表中的唯一字段

MYSQL GROUP BY 未显示正确的日期

python - 列上的 Pandas Multiindex Groupby

javascript - 检查 DOM 中的重复链接

r - 使用 R 一次在多列中查找重复项

mysql - 选择查询以显示具有最大日期的重复项

PHP 和 MySQL SESSION,最后一行

c# - 如何增加来自 c# 应用程序的 mysql 连接的连接超时?

mysql - 对文本列 : full-text or separate table 进行过滤

r - data.table:表中所有现有组合的总和