【发布时间】:2017-06-30 05:58:37
【问题描述】:
我正在努力创建一个选择查询,该查询将每一行合并/聚合为按列 postfix_id 分组的单行。
| postfix_id | initial_datetime | final_datetime | from_address | to_address | response |
| 655CB4B10 | 2017-06-30 00:17:13 | null | null | null | null |
| 655CB4B10 | null | null | bob@domain.tld | null | null |
| 655CB4B10 | null | null | null | sam@domain.tld | null |
| 655CB4B10 | null | 2017-06-30 00:17:14 | null | null | sent |
| C32AE57F3 | 2017-06-10 07:14:36 | null | null | null | null |
| C32AE57F3 | null | null | joe@domain.tld | null | null |
| C32AE57F3 | null | null | null | tye@domain.tld | null |
| C32AE57F3 | null | 2017-06-10 07:22:54 | null | null | bounce |
每个 postfix_id 值被列出 4 次,我需要将每个匹配项合并到一行中,从而删除剩余列中存在的空值。
例如所需的输出:
| postfix_id | initial_datetime | final_datetime | from_address | to_address | response |
| 655CB4B10 | 2017-06-30 00:17:13 | 2017-06-30 00:17:14 | bob@domain.tld | sam@domain.tld | sent |
| C32AE57F3 | 2017-06-10 07:14:36 | 2017-06-10 07:22:54 | joe@domain.tld | tye@domain.tld | bounce |
该表有超过一百万个独特的 postfix_id,我浏览过其他类似的帖子,但是,它们有要比较的列和/或不相关的列。我无数次使用 MAX 和 GROUP_CONCAT 的尝试都失败了。
任何帮助/指导将不胜感激。我觉得好像很简单,导致 /facepalm
再次感谢,我最终得到了以下内容以满足我的最终需求。我希望这对以后的人有所帮助..
SELECT postfix_id,from_address,to_address,remote_response,insert_datetime,initial_datetime,final_datetime
FROM (
SELECT
postfix_id,
MAX(from_address) AS from_address,
MAX(to_address) AS to_address,
MAX(remote_response) AS remote_response,
MAX(insert_datetime) AS insert_datetime,
MAX(initial_datetime) AS initial_datetime,
MAX(final_datetime) AS final_datetime
FROM email_outbound_postfix
GROUP BY
postfix_id
) as t1
WHERE insert_datetime >= DATE_SUB(NOW(),INTERVAL 1 DAY)
AND CONCAT(from_address, ' ', to_address) LIKE '%sam%';
【问题讨论】: