SQL Server Matching & Non Matching records with single query in SQL

ssgvzors  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(114)

I have a table in which it contains duplicate data based on multiple columns.I am looking to select the matching data based on multiple columns and at the same time non matching based on another column.

CREATE TABLE #table1
(
  id   INT,
  code VARCHAR(5),
  type VARCHAR(5)
)

INSERT INTO #table1(id,code,type)
SELECT 1,'AA','T' UNION ALL
SELECT 2,'AB','R' UNION ALL
SELECT 3,'AC','T' UNION ALL
SELECT 1,'AA','K' UNION ALL
SELECT 3,'AC','T' 

    
SELECT t.*
  FROM #table1 T
 INNER JOIN #table1 T2
    ON t.id = t2.id
   AND t.code = t2.code
   AND t.type <> t2.type

I tried by self join with matching fields equal and non matching fields not equal

ulydmbyx

ulydmbyx1#

Try this:

SELECT t1.ID, t1.CODE, t1.TYPE
      FROM Table1 t1
INNER JOIN Table1 t2
        ON t1.ID = t2.ID
       AND t1.CODE = t2.CODE
       AND t1.TYPE <> t2.TYPE

This query will return the rows from Table1 that have matching ID and CODE values but different TYPE values.

相关问题