我有三个表:
1> Table_A
2> Table_B
3> Table_C
表_A 包含以下内容
id(PK) ssn
--- ---
1 111
2 222
3 333
表_B 包含以下内容
id (PK) ssn details
---- --- ------
11 111 hi
22 222 hello
33 555 hi hello
44 666 hi hello hi
Table_C 包含以下内容
id(PK) ssn mobile flag
----- --- ------ ----
1X 555 9830 A
2X 555 9831 B
3X 666 9745 A
4X 666 9876 B
5X 777 3454 A
6X 777 8734 B
首先,我需要找到哪个 SSN 存在于 Table_B 但不存在于 Table_A 中
select
distinct b.ssn
from
Table_B b
where
b.ssn not in (select ssn from Table_A)
上面会给我记录
ssn
---
555
666
现在我需要从上面得到的 ssn(s) 对应的 Table_C 按以下方式打印,
ssn to_mobile from_mobile
--- --------- -----------
555 9830 9831
666 9745 9876
即,如果标志为 A,mobile 列将为 to_mobile,如果标志值为 B,则为 from_mobile。
我真的找不到出路了。请帮忙
最佳答案
使用 left join
获取 table_b 中不在 table_a 中的值,然后连接 table_c 并使用条件聚合。
select
b.ssn
,max(case when c.flag = 'A' then c.mobile end) to_mobile
,max(case when c.flag = 'B' then c.mobile end) from_mobile
from table_B b
left join table_A a on a.ssn=b.ssn
join table_C c on c.ssn=b.ssn
where a.ssn is null
group by b.ssn
这假设对于每个给定的 ssn,标志 A、B 各有一行。
关于sql - 使用 sql/postgresql 查询显示带有列名的条件输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40553870/