到目前为止,我已经使用了以下SQL代码。
DECLARE @Table1 TABLE (ID INT Identity (1,1), Col1 varchar(50), Col2 varchar(50))
INSERT INTO @Table1 (Col1, Col2)
VALUES ('CAN','ABCD'),('CAN','ABCE'),('CAN','MNPP'),('CAN','MNPP'),('EDG','MNPP')
DECLARE @Table2 TABLE (ID INT Identity (1,1), Col2 varchar(50), Col3 varchar(50))
INSERT INTO @Table2 (Col2, Col3)
VALUES ('ABCD','ABC'),('ABCE','ABC'),('MNPP','MNO')
;WITH TEST_CTE AS
(
SELECT T1.ID
, T1.Col1, T1.Col2 AS T1Col2, T2.Col2 AS T2Col2, T2.Col3
, ROW_NUMBER() OVER (PARTITION BY T1.Col1, T2.Col3 ORDER BY T1.ID) AS DuplicateRowNumber
, CASE WHEN COUNT(*) OVER (PARTITION BY T1.Col1, T2.Col3) > 1 THEN 1 ELSE 0 END IsMulitple
FROM @Table1 T1 INNER JOIN @Table2 T2 ON T1.Col2 = T2.Col2
)
SELECT * FROM TEST_CTE
我正在
ID Col1 T1Col2 T2Col2 Col3 DuplicateRowNumber IsMulitple
1 CAN ABCD ABCD ABC 1 1
2 CAN ABCE ABCE ABC 2 1
3 CAN MNPP MNPP MNO 1 1
4 CAN MNPP MNPP MNO 2 1
5 EDG MNPP MNPP MNO 1 0
我期待
ID Col1 T1Col2 T2Col2 Col3 DuplicateRowNumber IsMulitple
1 CAN ABCD ABCD ABC 1 1
2 CAN ABCE ABCE ABC 2 1
3 CAN MNPP MNPP MNO 1 0
4 CAN MNPP MNPP MNO 1 0
5 EDG MNPP MNPP MNO 1 0
我的目标: 只有当我有多个记录时,我的副本才会被查询,其中T1.Col1和T2.Col3值相同但是T1.Col2值不同。
谢谢
更新:让IsMultiple工作。无法找出DuplicateRowNumber
更新2:nvm以前的更新,对实时数据不起作用。
答案 0 :(得分:1)
或许这样的事情:
;with cte as
(
select t1.id, t1.col1, t1.col2, t2.col3, dense_rank() over(partition by t1.col1, t2.col3 order by t1.col2) DuplicateRowNumber
from @table1 t1
join @table2 t2 on t1.col2 = t2.col2
)
select *, sign(max(DuplicateRowNumber) over (partition by col1, col3)-1) Ismultiple
from cte