1

我有一个包含三列的 MySQL 表:

Userid         | Email               | Points
---------------------------------------------------------
1              | jdoe@company.com    | 20
2              | jdoe%40company.com  | 25
3              | rwhite@company.com  | 14
4              | rwhite%40company.com| 10

我想要做的是删除重复的电子邮件和合并点。我希望我的桌子看起来像这样:

Userid         | Email               | Points
---------------------------------------------------------
1              | jdoe@company.com    | 45
3              | rwhite@company.com  | 24

我的查询将如何返回我的愿望表?

任何人都知道如何做到这一点?

提前致谢!

4

2 回答 2

2

你在寻找这样的东西吗?

SELECT MIN(userid) userid, email, SUM(points) points
  FROM 
(
  SELECT userid, REPLACE(email, '%40', '@') email, points
    FROM table1
) q
  GROUP BY email

输出:

| 用户名 | 电子邮件 | 积分 |
|--------|--------|--------|
| 1 | jdoe@company.com | 45 |
| 3 | rwhite@company.com | 24 |

这是SQLFiddle演示


现在,如果您想就地删除表中的重复数据,您可以这样做

-- Fix emails
UPDATE table1
   SET email = REPLACE(email, '%40', '@')
 WHERE email LIKE '%\%40%';
-- Merge points for duplicate records
UPDATE table1 t JOIN
(
  SELECT email, SUM(points) points
    FROM table1
   GROUP BY email
  HAVING COUNT(*) > 1
) q ON t.email = q.email
   SET t.points = q.points;
-- Delete all duplicate records except ones with lowest `userid`
DELETE t 
  FROM table1 t JOIN
(
  SELECT MIN(userid) userid, email
    FROM table1
   GROUP BY email
  HAVING COUNT(*) > 1
) q ON t.email = q.email
 WHERE t.userid <> q.userid;

这是SQLFiddle演示

于 2013-08-29T05:55:03.813 回答
0

使用此查询假设您想要匹配电子邮件而不做任何修改

SELECT MIN(user_id), SUM(points)as points, email FROM table_name GROUP BY email
于 2013-08-29T06:01:02.867 回答