我有一个包含数据和结构的表:
+-----------+-----------+-----------+-----------+
| member_id | bank_name | bank_ac | ac_holder |
+-----------+-----------+-----------+-----------+
| 14 | | 012-000 | |
| 14 | | 012-001 | Andy |
| 14 | CR Bank | 012-002 | Jacky |
+-----------+-----------+-----------+-----------+
我需要的是选择一个条目,所有列都填充第一个非空值。为:
+-----------+-----------+-----------+-----------+
| member_id | bank_name | bank_ac | ac_holder |
+-----------+-----------+-----------+-----------+
| 14 | CR Bank | 012-000 | Andy |
+-----------+-----------+-----------+-----------+
我不知道如何开始。有人能给我建议吗?
ps:空字段不是NULL,它们是空字符串。 架构提供here
答案 0 :(得分:1)
您可以使用某些聚合
select member_id,
min(bank_name) bank_name,
min(bank_ac) bank_ac,
min(ac_holder) ac_holder
from demo
group by member_id
如果您的数据包含空值,例如''(注意null与''不相同),那么您可以将case子句放在聚合函数中以跳过这些类型的值
<击> 撞击>
<击>select member_id,
min(case when bank_name is not null and bank_name <> '' then bank_name end) bank_name,
min(case when bank_ac is not null and bank_ac <> '' then bank_ac end) bank_ac,
min(case when ac_holder is not null and ac_holder <> '' then ac_holder end) ac_holder
from demo
group by member_id
击> <击> DEMO 击>
您的问题的另一种解决方法
select member_id,
substring_index(group_concat(case when bank_name is not null and bank_name <> '' then bank_name end order by your_auto_increment_col asc) ,',',1) bank_name,
substring_index(group_concat(case when bank_ac is not null and bank_ac <> '' then bank_ac end order by your_auto_increment_col asc) ,',',1) bank_ac,
substring_index(group_concat(case when ac_holder is not null and ac_holder <> '' then ac_holder end order by your_auto_increment_col asc) ,',',1) ac_holder
from demo
group by member_id