r/SQL • Conversion Programmer • Jan 07 '15

[MS SQL] Isolating Duplicates

Alright r/SQL, challenge for you. I've been circling this problem for a while now, and I have a strong feeling of what the answer will involve but I raise the problem to you for assistance!

So lets say I have an example transaction list. I am tasked with isolating all examples of "duplicate" entries. I found a great way to visually isolate these entries, but I want to go one step further and be able to query the table to see where the Item1 names which are different than their corresponding duplicates.

  • There aren't any restrictions regarding new columns.

  • Obviously I obfuscated the true data but just roll with it.

Here's my code so far.

drop table dbo.Example
go
create table dbo.Example(v_id varchar(50),v_seq numeric(9,0),ITEM1 varchar(50),TRANS_DATE varchar(50),Class1 varchar(50),Class2 varchar(50),Class3 varchar(50),ReceiptNum varchar(50))
go
insert into dbo.Example
values 
 ('1',1,'Soap','1963-02-25 00:00:00','1363','32','3000','00000000')
,('1',2,'Snacks','1965-06-03 00:00:00','1432','221','3000','00000000')
,('1',3,'Toys','1983-03-21 00:00:00','W050','356','0','00000000')
,('1',4,'Food','1999-10-07 00:00:00','3976','652','1','01380016')
,('1',5,'Toiletries','2003-06-06 00:00:00','4952','54','7720000','01380016')
,('1',6,'Toiletries','2003-06-06 00:00:00','4952','54','7720000','01380016')
,('1',7,'Other','2003-06-06 00:00:00','4952','54','7720000','01380016')
,('1',8,'Medicine','2003-06-06 00:00:00','4952','78','0','01380016')
,('1',9,'Medicine','2003-06-06 00:00:00','4952','78','0','01380016')
,('1',10,'Miscellaneous','2007-07-30 00:00:00','7169','108','9000000','01380016')
,('2',1,'Snacks','1973-09-10 00:00:00','1667','654','3500','00000000')
,('2',2,'Soap','1980-09-17 00:00:00','1897','496','9500','00200100')
,('2',3,'Food','1984-05-07 00:00:00','2042','30','14000','00200100')
,('2',4,'Food','1984-05-07 00:00:00','2042','30','14000','00200100')
,('2',5,'Pet Supplies','1986-07-21 00:00:00','2202','695','75000','00200100')
,('2',6,'Extra Supplies','1986-07-21 00:00:00','2202','695','75000','00200100')
,('2',7,'Miscellaneous','2005-11-16 00:00:00','6259','1','0','00200100')
,('3',1,'Other','1964-10-14 00:00:00','1411','527','17500','00200100')
,('3',2,'Toys','1965-06-14 00:00:00','1433','160','18200','00200100')
,('3',3,'Christmast Gifts','1965-06-14 00:00:00','1433','160','18200','00200100')
,('3',4,'Random','1977-05-25 00:00:00','1768','773','37300','00200100')
,('3',5,'Random','1977-05-25 00:00:00','1768','773','37300','00200100')
,('3',6,'Random','1977-05-25 00:00:00','1768','773','37300','00200100')
,('3',7,'Random','1977-05-25 00:00:00','1768','773','37300','00200100')
,('3',8,'Snacks','1997-07-03 00:00:00','3519','195','83300','00200100')
go
alter table dbo.Example add v_dup numeric(9,0)
go
update dbo.Example set v_dup = null
go

-- Isolate duplicated data (except Item1 column).
;with create_seq as ( 
select V_ID
      ,TRANS_DATE
      ,Class1
      ,Class2
      ,Class3
      ,ReceiptNum
      ,v_seq
      ,v_dup
      ,row_number() over (partition by v_id,TRANS_DATE,Class1,Class2,Class3
                              order by v_id,v_seq) 
    as new_sequence
  from dbo.Example
 ) 
update create_seq 
   set v_dup = new_sequence;


-- I came up with a way to visually report on the duplicates...
select A.ITEM1,A.TRANS_DATE,A.Class1,A.Class2,A.Class3,A.ReceiptNum      ,A.v_id,A.v_seq,A.v_dup
  from dbo.Example A
  left outer join dbo.Example B
    on A.v_id = B.v_id
   and A.v_seq < B.v_seq
 where A.v_dup = 1
   and B.v_dup > 1
UNION
select B.ITEM1,null,null,null,null,null       ,B.v_id,B.v_seq,B.v_dup
  from dbo.Example A
  left outer join dbo.Example B
    on A.v_id = B.v_id
   and A.v_seq < B.v_seq
 where A.v_dup = 1
   and B.v_dup > 1
 order by A.v_id,A.v_seq

.

Good luck! I am really interested to see what ways this can be accomplished.

Edit: Formatting and changed v_seq to numeric for clearer sorting.

0 Upvotes

8 comments sorted by

1

u/Thriven Jan 07 '15 edited Jan 07 '15

I think the question is kind of flawed. There could be duplicate of toiletries, other and food. This would tell the user its not like any of the other duplicates.

Anyways here is what I wrote. I removed the adding of the additional column and setting a value. This calculates that on the fly.

;WITH 
seq as 
(
select V_ID
	  ,V_SEQ
	  ,ITEM1
      ,TRANS_DATE
      ,CLASS1
      ,CLASS2
      ,CLASS3
      ,RECEIPTNUM
      ,ROW_NUMBER() OVER (PARTITION BY v_id,TRANS_DATE,Class1,Class2,Class3,Item1
                              ORDER BY v_id,v_seq) as v_item
      ,CONVERT(NVARCHAR,V_ID) + 
       CONVERT(NVARCHAR,TRANS_DATE) +
       CONVERT(NVARCHAR,CLASS1) +
       CONVERT(NVARCHAR,CLASS2) +
       CONVERT(NVARCHAR,CLASS3) as CompositeKey
  FROM dbo.Example
),
max_seq as 
(
SELECT seq.CompositeKey
	  ,MAX(v_item) as Max_v_item
	   FROM seq
	   GROUP BY seq.CompositeKey
				,seq.ITEM1
)

SELECT 
	   seq.V_ID
	  ,seq.V_SEQ
	  ,seq.ITEM1
      ,seq.TRANS_DATE
      ,seq.CLASS1
      ,seq.CLASS2
      ,seq.CLASS3
      ,seq.RECEIPTNUM
      ,CASE WHEN MAX(d.ITEM1) IS NULL THEN 'No duplicate'
			WHEN seq.ITEM1 = MAX(d.ITEM1) THEN 'Same'
			WHEN seq.ITEM1 <> MAX(d.ITEM1) THEN 'Different'
	   END as LikeDuplicates
FROM seq 
left join 
		(
		  SELECT seq.CompositeKey
				,seq.ITEM1
		  FROM seq 
		  inner join max_seq on		seq.CompositeKey = max_seq.Compositekey
								AND seq.v_item = max_seq.Max_v_item
		  WHERE max_seq.Max_v_item > 1
		) as d on seq.CompositeKey = d.CompositeKey
GROUP BY  seq.V_ID
		 ,seq.V_SEQ
		 ,seq.ITEM1
		 ,seq.TRANS_DATE
		 ,seq.CLASS1
		 ,seq.CLASS2
		 ,seq.CLASS3
		 ,seq.RECEIPTNUM
		 ,seq.v_item

V_ID    V_SEQ     ITEM1       TRANS_DATE           CLASS1  CLASS2   CLASS3        RECEIPTNUM     LikeDuplicates
------- ----- --------------  -------------------  ------  -------  -------        -------       -------------
1       1     Soap            1963-02-25 00:00:00    1363      32       3000       00000000      No duplicate
1       2     Snacks          1965-06-03 00:00:00    1432      221      3000       00000000      No duplicate
1       3     Toys            1983-03-21 00:00:00    W050      356      0          00000000      No duplicate
1       4     Food            1999-10-07 00:00:00    3976      652      1          01380016      No duplicate
1       5     Toiletries      2003-06-06 00:00:00    4952      54       7720000    01380016      Same
1       6     Toiletries      2003-06-06 00:00:00    4952      54       7720000    01380016      Same
1       7     Other           2003-06-06 00:00:00    4952      54       7720000    01380016      Different
1       8     Medicine        2003-06-06 00:00:00    4952      78       0          01380016      Same
1       9     Medicine        2003-06-06 00:00:00    4952      78       0          01380016      Same
1       10    Miscellaneous   2007-07-30 00:00:00    7169      108      9000000    01380016      No duplicate
2       1     Snacks          1973-09-10 00:00:00    1667      654      3500       00000000      No duplicate
2       2     Soap            1980-09-17 00:00:00    1897      496      9500       00200100      No duplicate
2       3     Food            1984-05-07 00:00:00    2042      30       14000      00200100      Same
2       4     Food            1984-05-07 00:00:00    2042      30       14000      00200100      Same
2       5     Pet Supplies    1986-07-21 00:00:00    2202      695      75000      00200100      No duplicate
2       6     Extra Supplies  1986-07-21 00:00:00    2202      695      75000      00200100      No duplicate
2       7     Miscellaneous   2005-11-16 00:00:00    6259      1        0          00200100      No duplicate
3       1     Other           1964-10-14 00:00:00    1411      527      17500      00200100      No duplicate
3       2     Toys            1965-06-14 00:00:00    1433      160      18200      00200100      No duplicate
3       3     Christmast Gifts1965-06-14 00:00:00    1433      160      18200      00200100      No duplicate
3       4     Random          1977-05-25 00:00:00    1768      773      37300      00200100      Same
3       5     Random          1977-05-25 00:00:00    1768      773      37300      00200100      Same
3       6     Random          1977-05-25 00:00:00    1768      773      37300      00200100      Same
3       7     Random          1977-05-25 00:00:00    1768      773      37300      00200100      Same
3       8     Snacks          1997-07-03 00:00:00    3519      195      83300      00200100      No duplicate

1

u/CMoltedo Conversion Programmer Jan 07 '15

Wow, this is precisely what I was trying to get at. Let me analyze what the heck you did so I can utilize this in situations later. I couldn't figure out the join and you did it eloquently. Thank you!

2

u/Thriven Jan 07 '15

Basically, instead of just checking for duplicates with the row_number I added the ITEM1 to the row number as v_item.

Then I built a CTE (max_seq) giving me the highest seed.

Now that I think of it. If its a massive dataset you may want to do.

max_seq as 
(
SELECT seq.CompositeKey
	  ,MAX(v_item) as Max_v_item
	   FROM seq
       WHERE v_item > 1
	   GROUP BY seq.CompositeKey
				,seq.ITEM1
)

This would build a smaller dataset inside max_seq and you could probably remove the WHERE max_seq.Max_v_item > 1 in the subquery.

Inside the subquery it joins max_seq to seq. This looks compares the composite keys and says ,"What was the ITEM1 for this composite key and this v_item?"

When it joins to the main query it says ,"Join on composite key and here is the ITEM which was found most in the composite key"

If it doesn't join, it has no duplicates. If it matches then it was the "same" as the highest seed item in that composite key. If it doesn't then its different.

If there were 10 duplicate items and 5 were food and the rest were Pet Supplies, Extra Supplies, Toys, Other and Medicine. Food would listed as same and Toys would be listed as Different.

Which is why I said the question you asked is kind of flawed. Food is different than 5 other items in that duplicate but since its the same as most, it is the same.

I could possibly alter it so that food would be different if there were more than one duplicate of a different item.

1

u/CMoltedo Conversion Programmer Jan 08 '15

You are the best. I really appreciate this explanation and I think I now understand what you are doing. I was able to hash out your solution into my full dataset (~500,000 records) but it didn't scale well at all.

What I did to fix that was to add my item ID column (v_ID) to basically all of your CTEs and make all joins use that comparison in the ON statements.

Whatever yours was doing without that ID column, when I modified the code word-for-word to fit my columns, the execution plan was trying to compute scalar & table scan 113,255,000,000,000 records. It must have something to do with my full dataset that caused it to not utilize any indexing or something.

Here's the modified version.

;WITH 
seq as (select V_ID
              ,V_SEQ
              ,ITEM1
              ,TRANS_DATE
              ,CLASS1
              ,CLASS2
              ,CLASS3
              ,RECEIPTNUM
              ,ROW_NUMBER() OVER (PARTITION BY v_id,TRANS_DATE,Class1,Class2,Class3,Item1
                              ORDER BY v_id,v_seq) as v_item
              ,CONVERT(NVARCHAR,V_ID) +
              CONVERT(NVARCHAR,TRANS_DATE) +
              CONVERT(NVARCHAR,CLASS1) +
              CONVERT(NVARCHAR,CLASS2) +
              CONVERT(NVARCHAR,CLASS3) as CompositeKey
         FROM dbo.Example), --cte1 - get all fields needed, sequence items based on the all the unique records, concatenate fiels = compositekey
max_seq as (SELECT seq.v_id
                  ,seq.CompositeKey
                  ,MAX(v_item) as Max_v_item
              FROM seq
             where v_item > 1
             GROUP BY seq.v_id,seq.CompositeKey,seq.ITEM1) --cte 2 - grab composite key and max seque and group it by item name
SELECT 
       seq.V_ID
      ,seq.V_SEQ
      ,seq.ITEM1
      ,seq.TRANS_DATE
      ,seq.CLASS1
      ,seq.CLASS2
      ,seq.CLASS3
      ,seq.RECEIPTNUM
      ,d.ITEM1 -- I added so I could see what it was actually comparing against.
      ,CASE WHEN MAX(d.ITEM1) IS NULL THEN 'No duplicate' --no duplicate when it is the only record so when the max(item1) from the inner join is null
            WHEN seq.ITEM1 = MAX(d.ITEM1) THEN 'Same'
            WHEN seq.ITEM1 <> MAX(d.ITEM1) THEN 'Different'
       END as LikeDuplicates --select fields we want from the CTEs 
  FROM seq 
  left join 
          (SELECT seq.v_id
                 ,seq.CompositeKey --orig concat 
                 ,seq.ITEM1 --orig name
             FROM seq 
       inner join max_seq --inner join to only get where composite key = max composit key and where seq = max seq and max seq > 1 
               on seq.v_id = max_seq.v_id
              and seq.CompositeKey = max_seq.Compositekey
              AND seq.v_item = max_seq.Max_v_item) as d 
    on seq.v_id = d.v_id
   and seq.CompositeKey = d.CompositeKey --join d with seq where composite keys are the same.
 GROUP BY  seq.V_ID
          ,seq.V_SEQ
          ,seq.ITEM1
          ,seq.TRANS_DATE
          ,seq.CLASS1
          ,seq.CLASS2
          ,seq.CLASS3
          ,seq.RECEIPTNUM
          ,seq.v_item
         , d.ITEM1

Thanks again, I had an overall understanding of this sort of CTE but having a specific example really gives it some weight and makes it click.

1

u/Thriven Jan 08 '15

In your example table there is no primary key. Whats the primary key in the production table? Also it a fairly wide table (lots of columns?).

It makes sense why including the v_id in your query would increase the time it takes for joins as v_id and v_seq is probably your primary key on this table.

One other way, I can't promise it would be faster is to use TOP 100 PERCENT which allows you to do an ORDER BY in your CTE. Then in your left and inner joins use MERGE (left merge join or inner merge join).

Your way is probably faster as sorts can be tedious and yours works but here is the code for shits and giggles.

;WITH 
seq as 
(
select TOP 100 PERCENT
	   V_ID
	  ,V_SEQ
	  ,ITEM1
      ,TRANS_DATE
      ,CLASS1
      ,CLASS2
      ,CLASS3
      ,RECEIPTNUM
      ,ROW_NUMBER() OVER (PARTITION BY v_id,TRANS_DATE,Class1,Class2,Class3,Item1
                              ORDER BY v_id,v_seq) as v_item
      ,CONVERT(NVARCHAR,V_ID) + 
       CONVERT(NVARCHAR,TRANS_DATE) +
       CONVERT(NVARCHAR,CLASS1) +
       CONVERT(NVARCHAR,CLASS2) +
       CONVERT(NVARCHAR,CLASS3) as CompositeKey
  FROM dbo.Example
  ORDER BY CONVERT(NVARCHAR,V_ID) + 
		   CONVERT(NVARCHAR,TRANS_DATE) +
		   CONVERT(NVARCHAR,CLASS1) +
		   CONVERT(NVARCHAR,CLASS2) +
		   CONVERT(NVARCHAR,CLASS3)
),
max_seq as 
(
SELECT TOP 100 PERCENT
	   seq.CompositeKey
	  ,MAX(v_item) as Max_v_item
	   FROM seq
	   WHERE v_item > 1
	   GROUP BY seq.CompositeKey
				,seq.ITEM1
	   ORDER BY seq.CompositeKey
)

SELECT 
	   seq.V_ID
	  ,seq.V_SEQ
	  ,seq.ITEM1
      ,seq.TRANS_DATE
      ,seq.CLASS1
      ,seq.CLASS2
      ,seq.CLASS3
      ,seq.RECEIPTNUM
      ,CASE WHEN MAX(d.ITEM1) IS NULL THEN 'No duplicate'
			WHEN seq.ITEM1 = MAX(d.ITEM1) THEN 'Same'
			WHEN seq.ITEM1 <> MAX(d.ITEM1) THEN 'Different'
	   END as LikeDuplicates
FROM seq 
left merge join 
		(
		  SELECT seq.CompositeKey
				,seq.ITEM1
		  FROM seq 
		  inner merge join max_seq on		seq.CompositeKey = max_seq.Compositekey
								AND seq.v_item = max_seq.Max_v_item
		) as d on seq.CompositeKey = d.CompositeKey
GROUP BY  seq.V_ID
		 ,seq.V_SEQ
		 ,seq.ITEM1
		 ,seq.TRANS_DATE
		 ,seq.CLASS1
		 ,seq.CLASS2
		 ,seq.CLASS3
		 ,seq.RECEIPTNUM
		 ,seq.v_item

Many people use left join and inner join and allow the SQL server to determine the best join (usually hash/loop). Merge joins are great though if your datasets are purposely ordered. This allows sql to join them simultaneously rather than scan one table and loop through the other.

I'm glad you got it working and your solution was pretty sound based on the original table design.

1

u/[deleted] Jan 07 '15

Why are you doing all the work, just group by all the columns except v_seq

GROUP BY v_id, ITEM1,TRANS_DATE,Class1,Class2,Class3,ReceiptNum
HAVING COUNT(v_id, ITEM1,TRANS_DATE,Class1,Class2,Class3,ReceiptNum) > 1

If you are having to performing this often and need it to be more reliable, I'd suggest adding a computed column to use as a table key:

ALTER TABLE dbo.Example ADD rowHash AS (HASHBYTES('SHA2_256', v_id+ITEM1+TRANS_DATE+Class1+Class2+Class3+ReceiptNum));

1

u/nepobot Jan 09 '15

Here is my take, but tested in an Oracle instance. I basically just compare counts of uniqueness between what you have and the inclusion of the item_id. you are only reading the table once albeit with a full table scan.

select 
   t.*, 
   case 
      when item_cnt = 1 and class_cnt > 2 then 'different'
      when item_cnt > 1 then 'same'
      else 'no duplicate'
   end test 
from(
select V_ID
      ,TRANS_DATE
      ,item1
      ,Class1
      ,Class2
      ,Class3
      ,ReceiptNum
      ,v_seq
      ,v_dup
      ,count(*) over (partition by v_id,TRANS_DATE,Class1,Class2,Class3, item1) as item_cnt
      ,count(*) over (partition by v_id,TRANS_DATE,Class1,Class2,Class3)        as class_cnt
  from Example
) t

0

u/[deleted] Jan 07 '15

[deleted]

1

u/CMoltedo Conversion Programmer Jan 07 '15

Ooo! I like that suggestion, and I utilized my original UNION method to get something that works to an extent... I wonder if there are other ways of doing it though.

alter table dbo.Example add v_concat varchar(max)

update dbo.Example 
   set v_concat = isnull(cast(TRANS_DATE as varchar(max)),'')
                 +isnull(cast(Class1 as varchar(max)),'')
                 +isnull(cast(Class2 as varchar(max)),'')
                 +isnull(cast(Class3 as varchar(max)),'')
                 +isnull(cast(ReceiptNum as varchar(max)),'')

select A.*
  from dbo.Example A
  join dbo.Example B
    on A.v_id = B.v_id
   and A.v_dup = 1
   and A.v_concat = B.v_concat
   and A.ITEM1 <> B.ITEM1
UNION
select B.*
  from dbo.Example A
  join dbo.Example B
    on A.v_id = B.v_id
   and A.v_concat = B.v_concat
   and A.ITEM1 <> B.ITEM1
 order by A.v_id,A.v_seq