mysql - 查询在一个表中查找重复值

标签 mysql

我正在尝试编写一个查询来比较输入不同电子邮件的 5 个用户 ID,然后如果它找到输入同一电子邮件的两个不同用户 ID,它将显示一个包含他们使用的电子邮件的列,以及其他 5 个列显示它被两个用户使用的次数,而其他 3 个未在单个表中使用它的用户为 0。这是一个例子:

输入:

    IDs|Email              
    U1 |test@email        
    U2 |test1@email
    U1 |test1@email
    U3 |test1@email
    U4 |test@email
    U1 |test1@email

输出:

    Email        | ID1 | ID2 | ID3 | ID4 | ID5
    test@email   |  1  |  0  |  0  |  1  |  0
    test1@email  |  2  |  1  |  1  |  0  |  0

我一直在尝试这样做并尝试了所有可能的选项,例如 GROUP BY 和 self-JOIN 但它没有运行查询。 请帮我。提前致谢。

最佳答案

您可以使用条件聚合透视您的结果:

select email, 
       sum(case when ids = 'U1' then 1 else 0 end) as Id1,
       sum(case when ids = 'U2' then 1 else 0 end) as Id2,
       sum(case when ids = 'U3' then 1 else 0 end) as Id3,
       sum(case when ids = 'U4' then 1 else 0 end) as Id4,
       sum(case when ids = 'U5' then 1 else 0 end) as Id5
from yourtable
group by email

由于您使用的是 mysql,您还可以使用以下较短的版本:

select email, 
       sum(ids = 'U1') as Id1,
       sum(ids = 'U2') as Id2,
       sum(ids = 'U3') as Id3,
       sum(ids = 'U4') as Id4,
       sum(ids = 'U5') as Id5
from yourtable
group by email

关于mysql - 查询在一个表中查找重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713195/

相关文章:

php - Laravel Eloquent 模态 - 第一行?

php - 使用 phpmyadmin 插入的数据和一列不断重复我尝试的第一个测试用例的值

Mysql 唯一索引 o = ö?

mysql - 选择给定 start_datetime 和 end_datetime 的所有行

php - 使用时间戳计算员工的工作时间

mysql - 用于数据分析的 NoSql 或 MySQL

mysql - 定义MySQL中的默认日期值,类似于时间戳

python - 我的 Flask 应用程序中的错误 "The view function did not return a valid response. "在哪里?

mysql - 如何格式化这种日期?

mysql - 使用 3 个连接在一个查询中更新 2 个不同的表?