我想结合两个具有结构的表:
表1:Id,Name,Reference1,Position
表2:Id,Name,Reference2,ArtNr,Price,Position
现在到了困难的部分: 具有不同“参考”字段的所有字段必须位于该新表中。 “参考”字段在新表中必须是唯一的,因此不会有两个具有相同“参考”的项目。 但是:如果表1和表2中有相同参考的记录,则新记录必须具有表1中的“位置”。表1中但不在表2中的所有条目必须具有新的位置表1中[MAX(位置)增加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,姓名:测试,参考:123,职位:5
Id:2,姓名:Test2,参考:125,职位:7
表2:
Id:1,姓名:Test,Reference1:123,Position:1
Id:2,Name:Test3,Reference1:127,Position:2
期望的输出:
Id:1,姓名:测试,参考2:123,职位: 5
Id:2,Name:Test2,Reference2:125,Position:7
Id:3,姓名:Test3,参考2:127,职位: 9
答案 0 :(得分:2)
我尝试创建样本数据,它会为您提供所需的结果
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
答案 1 :(得分:1)
我找到了解决方案:
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