我有一个具有以下结构的表:
+----+------+------+----------------+---------------------+
| id | val1 | val2 | email | lastUpdated |
+----+------+------+----------------+---------------------+
| 1 | 0 | 3 | test@gmail.com | 2015-02-07 13:21:55 |
| 2 | 5 | 0 | test@gmail.com | 2015-02-07 09:12:27 |
+----+------+------+----------------+---------------------+
由于我所做的查询中存在错误,因此有多行具有相同的“电子邮件”值。我想为所有重复项合并val1,val2和lastUpdated(更大的值)。它会给出这样的结果:
+----+------+------+----------------+---------------------+
| id | val1 | val2 | email | lastUpdated |
+----+------+------+----------------+---------------------+
| 1 | 5 | 3 | test@gmail.com | 2015-02-07 13:21:55 |
+----+------+------+----------------+---------------------+
答案 0 :(得分:2)
假设除了一行外,所有valX
列都为零,
RENAME TABLE originalTable TO messedUpTable
;
CREATE TABLE originalTable
SELECT
id,
SUM(val1) AS val1,
SUM(val2) AS val2,
email,
MAX(lastUpdated) AS lastUpdated
FROM messedUpTable
GROUP BY email
;
-- check originalTable to be sure it is okay
;
DROP TABLE messedUpTable
如果您在originalTable
上有索引,则必须再次定义它们。
答案 1 :(得分:1)
select max(val1), max(val2), email, max(lastUpdated)
from your_table
group by email