我正在尝试编写一个查询来比较输入不同电子邮件的 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/