簡體   English   中英

加入SQL或MS-Access?

[英]join in sql or ms-access?

有一個這樣的表,格式為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和class =“ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM