有一个这样的表,格式为SQL或ms-access。
样本
ID ID2 name class example
1 10 John main
2 10
3 10
4 10 ~ is look at me.
5 20 Candice main
6 20
7 20 ~ is in Japan.
8 20 ~ is reading a book.
9 20
我需要将示例字段 (A) 中的"~"替换为与 A 具有相同 ID2 且类 = "main" 的名称字段的值。如何制作连接语法?
结果
ID ID2 name class example
1 10 John main
2 10
3 10
4 10 John is look at me.
5 20 Candice main
6 20
7 20 Candice is in Japan.
8 20 Candice is reading a book.
9 20
我认为
您的表配置不正确。
您正在使用的 ID 字段在表上重复其性能的事实表明数据库设计有些糟糕。
我认为在两个表之间拆分数据可能会得到更好的结果,一个包含示例,另一个包含"main"类。然后,您将能够通过使用 ID2 字段的简单连接来连接两个表。
select m.[name] & replace(b.example, "~", "") as combined
from sample as m
inner join sample as b on m.id2 = b.id2
where m.[class] = "main"
and b.example not null
尽管数据的结构很糟糕(无论出于何种原因),但要回答您的问题,您可以这样做:
SELECT
T1.[ID],
T1.[ID2],
T1.[name],
T1.[class],
iif(not isnull(T1.[Example]) and not isnull(T2.[Name]), Replace(T1.[Example], "~", T2.[Name]), null) As [Example]
FROM
Data T1
LEFT JOIN Data T2 ON (T1.[ID2] = T2.[ID2] AND T2.[Class]="main")
这依赖于以下假设:对于 ID2 的每个唯一值,只有一条 class=main 的记录(否则您将获得重复的行)。
如果不需要使用 JOIN,另一种选择是:
SELECT
[ID],
[ID2],
[name],
[class],
(iif(not isnull([example]), Replace([example], "~", nz((select top 1 [name] from Data T2 where T2.ID2 = T1.ID2 and T2.[class]="main" order by T2.[ID2]),"")),null)) as [ExampleNew]
FROM Data T1