0

到目前为止,我有以下 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 不能很好地处理实时数据。

4

1 回答 1

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

小提琴

于 2013-11-15T08:32:45.200 回答