AlHal2
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,Na me5,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,Na me5,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.
I'm using SQL Server 2005 and have 2 related questions.
Q1
I have a table like this.
Company ID, Name1,Name2,Name3,Name4,Na
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,Na
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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))
I think the problem with Q2 is the And operator as this query works.
select * from mytable WHERE Name1 NOT in (Coalesce (Name4, Name1))
ASKER
I got it to work using lots of Union statements
But ... assuming you inherited this DB design and can't change it ... the answer to question 1 looks like this:
Open in new window