Link to home
Start Free TrialLog in
Avatar of AlHal2
AlHal2Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Finding duplicate and non null values for the same primary key

Hi Experts,

I'm using SQL Server 2005 and have 2 related questions.

Q1

I have a table like this.

Company ID, Name1,Name2,Name3,Name4,Name5,Name6
1,A,B,C,D,E,F
2,A,B,A,D,F,E
3,F,B,B,D,A,E
4,D,B,A,C,E,C

Please could I have some SQL to highlight company IDs where a name field is duplicated.
In the example above the 6 name fields are different for the first row.
Name1 and Name3 are repeated for the second row.
Name 2 and Name3 are repeated for the third row.
The 6 name fields are different for the fourth row.

Therefore I want the SQL to highlight rows 2 and 3.

Q2.

Consider the following table

Company ID, Name1,Name2,Name3,Name4,Name5,Name6
1,A,,,,,
2,,,,E,,E
3,F,,,D,,
4,D,,,,,

Please can I have some SQL to highlight rows with more than one Name field.  In the above example only row 3 has more than one name value.  Although row 2 has more than one value it is the same value duplicated, so I'm only interested in row 3.
Avatar of Daniel Wilson
Daniel Wilson
Flag of United States of America image

This would be a ton easier with a normalized design.

But ... assuming you inherited this DB design and can't change it ... the answer to question 1 looks like this:
Select CompanyID from MyTable
WHERE Name1 in (Name2, Name3, Name4, Name5, Name6) OR
  Name2 in (Name1, Name3, Name4, Name5, Name6)OR
  Name3 in (Name1, Name2, Name4, Name5, Name6)OR
  Name4 in (Name1, Name2, Name3, Name5, Name6)OR
  Name5 in (Name1, Name2, Name3, Name4, Name6)OR
  Name6 in (Name1, Name2, Name3, Name4, Name5)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Daniel Wilson
Daniel Wilson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AlHal2

ASKER

Q1 is fine, but Q2 returns nothing.

I think the problem with Q2 is the And operator as this query works.

select * from mytable WHERE Name1 NOT in (Coalesce (Name4, Name1))
Avatar of AlHal2

ASKER

I got it to work using lots of Union statements