【发布时间】:2021-04-21 18:14:55
【问题描述】:
我的 sql 查询得到以下结果:
| id | sp_firstname | sp_lastname | member_firstname | member_lastname |
|---|---|---|---|---|
| 1 | NULL | NULL | John | Smith |
| 2 | Dejuan | McLaughlin | NULL | NULL |
| 2 | NULL | NULL | Jack | Sparrow |
| 3 | John | Walker | NULL | NULL |
| 3 | NULL | NULL | Sherlock | Holmes |
| 4 | Mellie | Durgan | NULL | NULL |
| 4 | NULL | NULL | John | Waston |
| 5 | Lucy | Snider | NULL | NULL |
而我需要实现的是:
| id | sp_firstname | sp_lastname | member_firstname | member_lastname |
|---|---|---|---|---|
| 1 | NULL | NULL | John | Smith |
| 2 | Dejuan | McLaughlin | Jack | Sparrow |
| 3 | John | Walker | Sherlock | Holmes |
| 4 | Mellie | Durgan | John | Waston |
| 5 | Lucy | Snider | NULL | NULL |
基本上,我需要以某种方式合并具有nulls 横向的行对。
查看 SO 答案后,我只能在需要用数字替换 NULL 值时找到此问题的变体,在这种情况下,人们使用 max 函数与 group by 结合使用。
但是,我的表中有多个联接,我的 NULL 值需要替换为字符串,而不是数字,因此 max 不会在这里真正起作用(正如我所想的那样)。
这是我的 sql 代码:
select
meeting.id,
(case when salesprofile.userid = "user".id then "user".firstname end) as sp_firstname,
(case when salesprofile.userid = "user".id then "user".lastname end) as sp_lastname,
(case when business.userid = "user".id then "user".firstname end) as member_firstname,
(case when business.userid = "user".id then "user".lastname end) as member_lastname
from
meeting
join project on project.id = meeting.projectid
left join business on business.id = project.businessid
left join salesprofile on salesprofile.id = meeting.salesprofileid
join "user" on "user".id = business.userid or "user".id = salesprofile.userid
group by
"user".id,
business.userid,
meeting.id,
salesprofile.userid;
这些名字和姓氏来自完全相同的user 表,但它们是根据同一个meeting 表中的不同关系获取的。
基本上,一个meeting 有两个users:member 和sp。而且我需要一种方法来与member 和sp 用户一起开会。
如何修改我的 sql 查询,以便它将这些带有交叉 nulls 的行对合并为一行,其中有数据,而没有 nulls?
【问题讨论】:
-
Max 可以很好地处理字符串。
标签: sql postgresql join