MySQL:在GROUP BY之后添加多个列?

问题描述 投票:0回答:1

我正在尝试执行以下操作:

SELECT 
  customer_entity.email,
  customer_entity.website_id 
FROM
  customer_entity 
  INNER JOIN 
    (SELECT 
      email 
    FROM
      customer_entity 
    GROUP BY email 
    HAVING COUNT(email) > 1) dupes 
    ON customer_entity.email = dupes.email  
GROUP BY customer_entity.`entity_id` 
ORDER BY customer_entity.email ;

以上查询返回以下结果:

email               website_id
[email protected]             1
[email protected]             2
[email protected]             3
[email protected]             4
[email protected]            1
[email protected]            2
[email protected]            4
[email protected]              1
[email protected]              2
[email protected]              3

但是我想要以下格式的数据:

email           website1    website2    website3    website4

[email protected]         1           2           3           4 
[email protected]        1           2           null        4
[email protected]          1           2           3           null

在这种情况下可以吗?

谢谢

mysql sql database group-by pivot
1个回答
1
投票
select email, max(website_id = 1) website_1, max(website_id = 2) website_2, max(website_id = 3) website_3, max(website_id = 4) website_4 from customer_entity group by email having count(*) > 1 order by email

请注意,这简化了您的原始查询-此处不需要自我联接。

此外,这在每列中输入0/1值,以指示该网站是否存在给定的电子邮件-我发现它比重复该列中的网站ID更有意义。
© www.soinside.com 2019 - 2024. All rights reserved.