![](/img/trans.png)
[英]Join/Union different columns without duplicates (Distinct) into a new table
[英]UNION two tables with different columns, without duplicates, and update a field on union
我想結合兩個表與結構:
表1:ID,名稱,引用1,位置
表2:編號,名稱,參考2,ArtNr,價格,排名
現在到困難的部分:具有不同“引用”字段的所有字段都必須在該新表中。 “引用”字段在新表中必須是唯一的,因此不會有兩個項目具有相同的“引用”。 但是:如果在表1和表2中有一條引用相同的記錄,則新記錄必須具有表1的“位置”。所有不在表1中但在表2中的條目必須具有一個新位置,並且表1的[MAX(Position)遞增1]的值。
我沒有想法,如何解決這個問題:)感謝您的幫助!
編輯:
結合兩者:
Select Id, Name, Reference, null as ArtNr, null as Price, Position FROM Table1
Union
Select Id, Name, Reference, ArtNr, Price, Positionfrom Rechnung_Item FROM Table2
但這顯示了兩個表的所有條目...
樣本數據:
表格1:
ID:1,名稱:Test,參考號:123,位置:5
ID:2,名稱:Test2,引用:125,位置:7
表2:
編號:1,名稱:測試,參考編號:123,位置:1
ID:2,名稱:Test3,參考號:127,位置:2
所需的輸出:
ID:1,名稱:Test,參考號2:123,位置: 5
ID:2,名稱:Test2,引用2:125,位置:7
Id:3,名稱:Test3,引用2:127,位置: 9
我嘗試創建示例數據,它可以為您提供所需的結果
declare @temp1 as table (Id int , Name varchar(50), Reference int, Position int)
insert into @temp1 (Id ,Name , Reference , Position ) values (1,'A',123,5)
insert into @temp1 (Id ,Name , Reference , Position ) values (2,'B',125,7)
--insert into @temp1 (Id ,Name , Reference , Position ) values (1,'C','Ref3',1)
declare @temp2 as table (Id int , Name varchar(50), Reference int, Position int, ArtNr int )
insert into @temp2 (Id ,Name , Reference , Position,ArtNr ) values (1,'A',123,1,1)
insert into @temp2 (Id ,Name , Reference , Position,ArtNr ) values (1,'C',127,2,2)
--insert into @temp2 (Id ,Name , Reference , Position,ArtNr ) values (1,'B',128,1,3)
--insert into @temp2 (Id ,Name , Reference , Position ,ArtNr) values (1,'C','Ref5',2,4)
select isnull(r1 ,r2) as Reference ,
ISNULL(n1,n2) as name , newPosition as Position
from (
select t1.Reference as r1 ,t2.Reference as r2 , t1.Name as n1 , t2.Name as n2 ,
case when t1.Position is not null then t1.Position else (select max(Position)+ t2.Position from @temp1)
end as newPosition
from @temp1 t1 full outer join @temp2 t2 on t1.Reference = t2.Reference
) as tr
我制定了解決方案:
SELECT * FROM (
SELECT Id, Name, Reference1 as Reference, Position FROM Table1
UNION ALL
SELECT Id, Name, Reference2 as Reference, Position + (SELECT MAX(Position) FROM Table1) FROM Table2) as result GROUP BY Reference
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.