Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

tsql - SQl server duplicate joins issue with different elements

Sorry, I am posting again with one more requirement.

can anyone please help: I tried to join with duplicate values but it is not coming as I wanted.

DROP TABLE IF EXISTS #TestTable1
DROP TABLE IF EXISTS #TestTable2

CREATE TABLE #TestTable1 ([No] varchar(50),[Value1] float,[Desc] varchar(50))
insert into #TestTable1 ([No],[Value1],[Desc])
Values 
 (N'123953',300.02,N'Extra Pay')
,(N'123953',427.2,N'Basic Hours')
,(N'123953',106.8,N'Basic Hours')
,(N'123953',213.6,N'Basic Hours')
,(N'123953',213.6,N'Basic Hours')
,(N'123953',213.6,N'Basic Hours')
,(N'123953',213.6,N'Basic Hours')
,(N'123953',105.6,N'Basic Hours')


CREATE TABLE #TestTable2 ([No] varchar(50),[Value2] float,[Desc] varchar(50))
insert into #TestTable2 ([No],[Value2],[Desc])
Values 
 (N'123953',200.02,N'Extra Pay')
,(N'123953',553.02,N'Basic Hours')
,(N'123953',446.67,N'Basic Hours')
,(N'123953',427.2,N'Basic Hours')
,(N'123953',106.8,N'Basic Hours')
,(N'123953',213.6,N'Basic Hours')
,(N'123953',213.6,N'Basic Hours')
,(N'123953',213.6,N'Basic Hours')
,(N'123953',105.6,N'Basic Hours')

Desired Output:

[No],[Desc],[Value1],[Value2],[MatchResult]


,(N'123953',N'Extra Pay',300.02,200.02, False)
,(N'123953',N'Basic Hours',427.2,427.2, True)
,(N'123953',N'Basic Hours',106.8,106.8, True)
,(N'123953',N'Basic Hours',213.6,213.6, True)
,(N'123953',N'Basic Hours',213.6,213.6, True)
,(N'123953',N'Basic Hours',213.6,213.6, True)
,(N'123953',N'Basic Hours',213.6,NULL,NULL)
,(N'123953',N'Basic Hours',105.6,105.6, True)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

--it looks to me like you should be able to force row_numbers onto duplicate rows, and therfore achieve a one-to-one join, leaving no match on the right as null

SELECT Q1.No, Q1.[desc], Q1.[value1],q2.[value2] FROM 

 (SELECT [NO] , 
            value1, 
            [desc], 
            ROW_NUMBER() over(partition by [NO] , value1, [desc] order by [no]) RN 
                FROM #TestTable1
  ) Q1

 LEFT JOIN

 (SELECT [NO] , 
            value2, 
            [desc], 
            ROW_NUMBER() over(partition by [NO] , value2, [desc] order by [no]) RN 
                FROM #TestTable2
  ) Q2

 ON Q1.Value1=Q2.Value2 AND 
        Q1.[No] = Q2.[NO] AND 
            Q1.[desc] = Q2.[Desc] AND 
                Q1.RN = Q2.rn

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...