首页 > 解决方案 > 是否可以在 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。

标签: mysqlsqlmerge

解决方案


你似乎想要一个扭曲的聚合:

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。

请注意,在您的示例数据中,其中一个paidorprice始终是NULL。如果有异常,则此代码可能不起作用。如果是这种情况,我建议您使用适当的样本数据和期望的结果提出一个问题。


推荐阅读