基于优先级规则关联Customers与Addresses表并返回单条客户记录
需求:关联Customers与Addresses表并按规则返回唯一记录
关联规则
- 优先选取
isPrimary为1的主地址; - 若无主地址,则选取
address_line以字母'A'开头的地址(多条仅取一条); - 若上述条件均不满足,则地址相关字段留空。
Customers表结构
| customer_id | first_name | last_name |
|---|---|---|
| 1 | John | Johnny |
| 2 | Mike | Mikey |
| 3 | Tim | Timson |
| 4 | Bart | Bartson |
Addresses表结构
| address_id | customer_id | address_line | city | isPrimary |
|---|---|---|---|---|
| 1 | 1 | "Address line" | Toronto | 0 |
| 2 | 1 | "Another address" | Chicago | 1 |
| 3 | 2 | "6th ave." | Los Angel | 0 |
| 4 | 2 | "Just an address" | Salt Lake | 0 |
| 5 | 3 | "Tim's street" | Denver | 1 |
| 6 | 3 | "Another Tim's ad" | Berlin | 1 |
| 7 | 4 | "Wallstreet" | New York | 0 |
| 8 | 4 | "Skystreet" | London | 0 |
| 9 | 4 | "St. Angel str." | Rome | 0 |
| 10 | 2 | "Another Mike's" | London | 0 |
预期输出
| customer_id | first_name | last_name | address_line | city |
|---|---|---|---|---|
| 1 | John | Johnny | "Another address" | Chicago |
| 2 | Mike | Mikey | "Another Mike's" | London |
| 3 | Tim | Timson | "Tim's street" | Denver |
| 4 | Bart | Bartson | "" | "" |
规则说明
- John有两个以'A'开头的地址,但存在主地址,故选取主地址;
- Mike的3个地址均非主地址,故选取以'A'开头的地址;
- Tim有两个主地址,仅选取第一条;
- Bart的地址既非主地址也不以'A'开头,故地址字段留空。
解决方案(SQL)
使用窗口函数ROW_NUMBER()按优先级为每个客户的地址排序,再关联主表获取结果:
WITH ranked_addresses AS ( SELECT customer_id, address_line, city, ROW_NUMBER() OVER ( PARTITION BY customer_id ORDER BY -- 优先级1:主地址排最前 CASE WHEN isPrimary = 1 THEN 0 ELSE 1 END, -- 优先级2:以A开头的地址次之 CASE WHEN address_line LIKE 'A%' THEN 0 ELSE 1 END, -- 同优先级下取address_id最小的记录 address_id ) AS rn FROM Addresses ) SELECT c.customer_id, c.first_name, c.last_name, -- 无匹配地址时用空字符串填充 COALESCE(ra.address_line, '') AS address_line, COALESCE(ra.city, '') AS city FROM Customers c LEFT JOIN ranked_addresses ra ON c.customer_id = ra.customer_id AND ra.rn = 1;
代码解释
- CTE
ranked_addresses:为每个客户的地址分配排序号rn,排序规则严格遵循需求:主地址优先,其次是A开头的地址,同级别地址按address_id取最早的一条。 - 主查询:左连接
Customers表和排序后的地址表,只取每个客户的第一条排序记录(rn=1),用COALESCE将无匹配地址的字段转为空字符串,符合预期输出要求。
内容的提问来源于stack exchange,提问作者Kristiyan Kotomanov
相关产品推荐
相关产品推荐

