SQL Select - identify record discrepancies

tmajor99
tmajor99 used Ask the Experts™
on
I need some help with SQL Select to identify record discrepancies.  I have a table containing a list of products with each product containing 3 feature descriptions.  I also have a group ID column that groups related sets of products together.  WIthin each product group, I need to identify the group of products that do not contain the same set of new features.    For example;

GroupID  Product ID NewFeature01 NewFeature02 NewFeature03
  1                  21                   Apple            Peach
  1                  22                   Peach            Apple
  1                  23                                          Peach               Apple
  2                  24                    Cherry
  2                  25                    Orange  
  3                  26                                          Nuts
  3                  27                     Nuts

Using the above example, only product group does not have the same set of new features.   Therefore, the expect result from this SQL Select query would:
GroupID  Product ID NewFeature01 NewFeature02 NewFeature03
  2                  24                    Cherry
  2                  25                    Orange
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Team Lead
Commented:
probably still not the best solution but something like this seems working for me.

declare @yourTable table
(
	GroupID int,
	[Product ID] int,
	NewFeature01 varchar(50),
	NewFeature02 varchar(50),
	NewFeature03 varchar(50)
);
insert into @yourTable 
values
(1, 21, 'Apple', 'Peach', null),
(1, 22, 'Peach', 'Apple', null),
(1, 23, null, 'Peach', 'Apple'),
(2, 24, 'Cherry', null, null),
(2, 25, 'Orange', null, null),
(3, 26, null, 'Nuts', null),
(3, 27, 'Nuts', null, null),

(4, 28, 'Apple', 'Peach', null),
(4, 29, 'Peach', 'Apple', null),
(4, 30, 'whatever', 'Peach', 'Apple');

with cte as
(
	select GroupID, NewFeature, count(NewFeature) Cnt,
	rank() over (partition by GroupID order by count(NewFeature)) idx
	from
	(
		select GroupID, NewFeature01 as NewFeature from @yourTable
		union all
		select GroupID, NewFeature02 from @yourTable
		union all
		select GroupID, NewFeature03 from @yourTable
	) a
	where NewFeature is not null
	Group by GroupID, NewFeature
), cte2 as
(
	select groupid
	from cte
	where cnt = 1 or idx > 1
	group by groupid
)
select a.*
from @yourTable a
inner join cte2 b
on a.groupid = b.groupid
order by GroupID

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial