任何人都可以帮忙吗:我试图加入重复的值,但并没有达到我想要的水平。
CREATE TABLE #TestTable1 ([No] varchar(50),[Value1] float,[Desc] varchar(50))
insert into #TestTable1 ([No],[Value1],[Desc])
Values
(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',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')
所需的输出:
[No],[Desc],[Value1],[Value2]
(N'123953',N'Basic Hours',427.2,427.2)
,(N'123953',N'Basic Hours',106.8,106.8)
,(N'123953',N'Basic Hours',213.6,213.6)
,(N'123953',N'Basic Hours',213.6,213.6)
,(N'123953',N'Basic Hours',213.6,213.6)
,(N'123953',N'Basic Hours',213.6,NULL)
,(N'123953',N'Basic Hours',105.6,105.6)
注意:由于其他原因,我无法加入“值”字段。
我尝试使用row_number()
,但仍然不能作为所需的输出。
预先感谢。
答案 0 :(得分:2)
这里是获得所需输出的一种方法:
;WITH CTE1 AS
(
SELECT [No],
[Value1],
[Desc],
ROW_NUMBER() OVER(PARTITION BY [No], [Value1] ORDER BY @@SPID) As rn
FROM #TestTable1
), CTE2 AS
(
SELECT [No],
[Value2],
[Desc],
ROW_NUMBER() OVER(PARTITION BY [No], [Value2] ORDER BY @@SPID) As rn
FROM #TestTable2
)
SELECT C1.[No],
C1.[Desc],
C1.[Value1],
C2.[Value2]
FROM CTE1 AS C1
LEFT JOIN CTE2 AS C2
ON C1.[No] = C2.[No]
AND C1.rn = C2.rn
AND C1.[Value1] = C2.[Value2]
答案 1 :(得分:1)
这看起来如何?
WITH Table1
AS
(
SELECT T1.No,
T1.[Desc],
T1.Value1,
CAST(T1.Value1 AS VARCHAR) + '~' + CAST(ROW_NUMBER() OVER (PARTITION BY T1.No, T1.Value1 ORDER BY T1.Value1 ASC) AS VARCHAR(2)) AS RN
FROM @TestTable1 AS T1
),
Table2
AS
(
SELECT T2.No,
T2.[Desc],
T2.Value2,
CAST(T2.Value2 AS VARCHAR) + '~' + CAST(ROW_NUMBER() OVER (PARTITION BY T2.No, T2.Value2 ORDER BY T2.Value2 ASC) AS VARCHAR(2)) AS RN
FROM @TestTable2 AS T2
)
SELECT T.No,
T.[Desc],
T.Value1,
T2.Value2
FROM Table1 AS T
LEFT
JOIN Table2 AS T2
ON T.No = T2.No
AND T.RN = T2.RN;