Conditional Join 查找特定值作为首选项,但除此之外接受其他值

Conditional Join that looks for a specific value as a preference, but otherwise accepts other values

假设我有一些客户拥有多个 phone 号码,而一些客户只有一个号码。只要有多个数字,其中一个数字旁边就会 总是 设置等于 'MAIN' 的类型列。但是如果没有多个数字,那么 Type 可以等于任何东西。在 T-SQL 中,在有多个号码的情况下,如何选择标记为 'MAIN' 的号码,而在没有号码的情况下,只有 select 是唯一可用的号码多个号码。谢谢!

在连接上使用子查询是理想的..但我似乎无法理解。

客户表: |编号 |姓名 |
| --- | ----- | |编号 | ACME公司 | | 1 | Foo 栏 |

电话表:

CustID Type Phone
1 blah 12345
2 NULL 33333
2 MAIN 98765

期望的输出:

1, 12345
2、98765

加入 phone table 两次 - 首先是 MAIN phone,然后是任何 phone,然后使用 coalesce() 获得第一个(即非空)命中:

select
  c.id,
  max(coalesce(p.phone, p2.phone)) as phone_number
from customer c
left join phone_table p on p.cust_id = c.id
  and p.type = 'MAIN'
left join phone_table p2 on p2.cust_id = c.id
group by c.id

max()用于return一行只有在有很多非主要phone号码的情况下。如果你想要全部,删除 maxgroup by

请注意,条件 p.type = 'MAIN' 必须 在连接条件中(而不是在 where 子句中)才能起作用。

如果您将条件放在 where 子句中,它将强制到 p 的连接成为 inner 连接,而客户没有 MAIN phone 不会被 return 编辑。