mysql - 是否可以在 mysql 中将 2 行合并为 1 行?
问题描述
我需要将表中的多行(基于条件的 2 行)合并为一个,基于:
相同的 custid 和相同的 appdate 和价格 = 已支付
并有欲望输出。
我现在的数据:
tbla
appid custid appdate price paid
1 1 10/10/20 20 null
2 2 10/10/20 10 null
3 1 11/10/20 30 null
4 3 12/10/20 20 null
5 1 13/10/20 20 null
6 1 10/10/20 null 20
7 2 11/10/20 null 10
8 1 11/10/20 null 20
9 3 12/10/20 null 20
10 1 13/10/20 null 20
得意输出:
tblb
appid custid appdate price paid
1 1 10/10/20 20 20 => same custid, same appdate, price=paid
2 2 10/10/20 10 null
3 1 11/10/20 30 null
4 3 12/10/20 20 20 => same custid, same appdate, price=paid
5 1 13/10/20 20 20 => same custid, same appdate, price=paid
7 2 11/10/20 null 10
8 1 11/10/20 null 20
不要为 appid 烦恼。我最终将通过创建一个新表来重建 appid。
解决方案
你似乎想要一个扭曲的聚合:
select min(appid) as appid, custid, appdate,
max(price) as price, max(paid) as paid
from tbla
group by custid, appdate, coalesce(price, paid);
扭曲将price
/paid
视为单列。
这是一个 db<>fiddle。
请注意,在您的示例数据中,其中一个paid
orprice
始终是NULL
。如果有异常,则此代码可能不起作用。如果是这种情况,我建议您使用适当的样本数据和期望的结果提出一个新问题。
推荐阅读
- postgresql - Sqlx 只接受查询宏中的字符串文字,如何使用变量?
- javascript - JS 新的 FormData 将未定义添加到值
- reactjs - 在 React 中将数据从父级传递给子级
- python - 烧瓶 sqlalchemy 将 .h5 文件保存/加载到数据库
- selenium - 詹金斯没有按预定时间运行
- python - 在 Pandas 的低频 bin 中对高频数据进行计算
- alsa - ALSA:snd_pcm_writei 如何影响音频输入
- javascript - Javascript - 如何仅将已从电子表格 B 修改的数据行附加到电子表格 A
- jquery - 循环表单并使用 jQuery 使用 AJAX 提交
- visual-studio-code - 从 winSCP 打开文件时,VScode 在标签栏中显示(已删除)