将许多唯一行合并为一个

时间:2017-06-30 05:58:37

标签: mysql sql merge subquery

我正在努力创建一个选择查询,将每行合并/聚合到按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次,我需要将每个匹配项合并为一行,从而删除其余列中的空值。

e.g。期望的输出:

|   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%';

2 个答案:

答案 0 :(得分:1)

如果您向我们展示的数据准确无误,那么您只需在postfix_id列上汇总表格,然后选择每个其他列的MAX()

SELECT
    postfix_id,
    MAX(initial_datetime) AS initial_datetime,
    MAX(final_datetime)   AS final_datetime,
    MAX(from_address)     AS from_address,
    MAX(to_address)       AS to_address
FROM yourTable
GROUP BY
    postfix_id

这应该起作用的原因是MAX() 忽略列中的 NULL值。因此,假设每个postfix_id组只有一个非NULL值,那么MAX()会选择它。

<强>输出:

enter image description here

在这里演示:

Rextester

答案 1 :(得分:1)

为此你可以简单地使用Mysql的MAX

 SELECT postfix_id , MAX(initial_datetime) AS initial_datetime ,MAX(final_datetime) AS final_datetime ,MAX(from_address) AS  from_address ,MAX(to_address) AS to_address,MAX(response) AS response from table group by postfix_id 

有关MAX的更多信息,请阅读https://dev.mysql.com/doc/refman/5.7/en/example-maximum-column.html