Select rows with same id but different value in another column

后端 未结 8 1619
名媛妹妹
名媛妹妹 2020-12-08 01:50

I tried for hours and read many posts but I still can\'t figure out how to handle this request:

I have a table like this:

+------+------+
|ARIDNR|LIE         


        
8条回答
  •  情深已故
    2020-12-08 02:31

    This is an old question yet I find that I also need a solution for this from time to time. The previous answers are all good and works well, I just personally prefer using CTE, for example:

    DECLARE @T TABLE (ARIDNR INT, LIEFNR varchar(5)) --table variable for loading sample data
    INSERT INTO @T (ARIDNR, LIEFNR) VALUES (1,'A'),(2,'A'),(3,'A'),(1,'B'),(2,'B'); --add your sample data to it
    WITH duplicates AS --the CTE portion to find the duplicates
    (
        SELECT ARIDNR FROM @T GROUP BY ARIDNR HAVING COUNT(*) > 1
    )
    SELECT t.* FROM @T t --shows results from main table
    INNER JOIN duplicates d on t.ARIDNR = d.ARIDNR --where the main table can be joined to the duplicates CTE
    

    Yields the following results:

    1|A
    1|B
    2|B
    2|A

提交回复
热议问题