![](/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.