[英]Turn a delimited field of ids into their pretty values - Are nested replaces the best option?
考虑以下两个表
客户
ID | 客户名称 |
---|---|
1 | 亚当 |
2 | 史蒂夫 |
3 | 杰克 |
4 | 哈维 |
产品
姓名 | 客户 |
---|---|
一个 | 1,2,3,4 |
乙 | 1,3,4 |
C | 2 |
D | 1,3 |
如何进行查询,将 Products.Clients 字段替换为 Clients.Client_Name 的分隔字符串而不是 Clients.ID?
期望的查询结果
姓名 | 客户 |
---|---|
一个 | 亚当、史蒂夫、杰克、哈维 |
乙 | 亚当、杰克、哈维 |
C | 史蒂夫 |
D | 亚当,杰克 |
以下使用嵌套替换的方法有效,但对我来说这不是“正确”的方式,特别是因为在我的情况下,每行可能有超过 4 个值 - 有什么更好的吗?
SELECT NAME, REPLACE(REPLACE(REPLACE(REPLACE(CLIENTS,1,'Adam'),2,'Steve'),3,'Jack'),4,'Harvey') FROM PRODUCTS
我应该注意,我实际上不会做Replace(clients, 1, 'adam')
而是Replace(clients, 1, SELECT CLIENT_NAME FROM CLIENTS WHERE ID = 1)
但是对于这个问题的 scope,我或多或少写了 psuedocode .
您不应该以这种格式存储您的数据。 应该有一个单独的表,比如product_clients
来存储两个实体之间的关系,每个不同的产品/客户元组有一行。
对于您当前的设计和版本,您最好的选择可能是递归查询,以迭代遍历并用相应的名称替换客户端 ID:
with prod as (
select
p.name,
p.clients + ',' as clients,
cast('' as varchar(max)) as new_clients
from products p
union all
select
p.name,
substring(p.clients, charindex(',', p.clients) + 1, len(p.clients)),
p.new_clients + ',' + c.client_name
from prod p
inner join clients c on c.id = left(p.clients, charindex(',', p.clients) - 1)
where charindex(',', p.clients) > 0
)
select name, stuff(max(new_clients), 1, 1, '') as new_clients
from prod
group by name
name | new_clients :--- | :--------------------- A | Adam,Steve,Jack,Harvey B | Adam,Jack,Harvey C | Steve D | Adam,Jack
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.