样本数据
id_type,seq_no,acct_name,_acct#,address
12345,67,jiimm,,167 s.40th st
12345,67,jiimm joe the 3rd,,167 s.40th st
12345,67,jiimm
12345,67,,0981_1,po box 1234
12345,80,Lee,,1234 street ave
12345,80,Lee
12345,80,,588_1,109 road st
代码
SELECT `ID`_type,
seq_no,
MAX(`acct_name`) AS acct_name,
MAX(`acct_#`) AS acct_#,
address
FROM `test_table`
GROUP BY `ID`_type,
seq_no;
<小时/>
我想根据 id_type 和 seq_no 合并行。我使用 max 来合并行,但由于 MAX acct#,我会覆盖任何现有地址和 acct_names。
我的结果
id_type,seq_no.,acct_name,_acct#,address
12345,67,jiimm joe the 3rd,0981_1,167 s.40th st
12345,80,Lee,588_1,109 road st
- 丢失 67 号邮政信箱 1234-
- 失去 1234 街大道为 80,失去 jiimm-
期望的结果
12345,80,Lee,588_1,109 road st
12345,80,Lee,588_1,1234 street ave
12345,67,jiimm,0981_1,167 s.40th st
12345,67,jiimm,0981_1,po box 1234
12345,67,jiimm joe the 3rd,0981_1,167 s.40th st
最佳答案
这为您提供了您正在寻找的内容,但请阅读上面问题下方的我的评论/问题。有一种模棱两可的“从多行中选择一行”的情况需要澄清。在这种模棱两可的情况下,您暗示规则要求提供最小的非空白帐户名称,此代码就是这样做的,但您可以看到它如何需要以一种方式处理帐户名称,并以不同的方式处理 acct (#) 和地址方式。我认为您正在寻找一个根据难以记住的规则提供结果的应用程序。即使您发布了上述处理规则,类似的时髦规则最终也会被报告为缺陷。因此,您可能希望增强捕获此数据的上游流程,以提供更规范的数据。
SQLFIDDLE link - 简而言之,内部查询填充缺失值,然后外部结果集提供不同的行。我用不为空的空白值对此进行了测试。我确实快速添加了处理空值的代码,但我没有使用空值对其进行测试,因此我建议如果生产将使用空值,则对其进行测试。
select distinct * from (
select d.id_type, d.seq_no
,coalesce( nullif( acct_name, ''), min_acct_name ) as merged_acct_name
,coalesce( nullif( acct, ''), max_acct ) as merged_acct
,coalesce( nullif( address, ''), max_address ) as merged_address
from test_table d
left join ( select id_type, seq_no
,max( acct ) as max_acct
,max( address ) as max_address
from test_table
group by id_type, seq_no
) as max_
on max_.id_type = d.id_type and max_.seq_no = d.seq_no
and ( coalesce( d.acct,'' ) = ''
or coalesce( d.address,'' ) = '' )
left join ( select id_type, seq_no
,min( acct_name ) as min_acct_name
from test_table
where coalesce( acct_name, '' ) <> ''
group by id_type, seq_no
) as min_
on min_.id_type = d.id_type and min_.seq_no = d.seq_no
and coalesce( d.acct_name,'' ) = ''
) as t
order by id_type, seq_no desc, merged_acct_name, merged_acct, merged_address
关于mysql - 合并同一个表sql中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26981671/