How to query using derived table and multi CTEs...

Having temp table #t contain:
Product  ProdType
A            x
B            x
B            xx
C            x
D            x
D            xx
E            x

Question: Using derived table and also CTEs (2nd solution), How to produce result like:
ProdType  ProdType
B            x
B            xx
D            x
D            xx

These solutions basically ignore products with single ProdType?

T-SQL to build #t:
create table #t(Product char(1), ProdType varchar(2));
Insert into #t(Product, ProdType) Values
('A', 'x')
, ('B', 'x')
, ('B', 'xx')
, ('C', 'x')
, ('D', 'x')
, ('D', 'xx')
, ('E', 'x');

Select * From #t;

Open in new window

LVL 34
Mike EghtebasDatabase and Application DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike EghtebasDatabase and Application DeveloperAuthor Commented:
Derived table solution:
Select Product, ProdType
from (
  select *, count(*) over (partition by Product) cnt from #t
) d where cnt > 1;

Solution using multiple CTEs:
With d
Select row_number()  over(partition by Product order by ProdType) As rn
, Product
From #t),
Select #t.Product, ProdType, d.rn
From #t inner join d on d.Product = #t.Product
Where d.rn >=2)
Select e.Product, e.ProdType
From e;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
Note to experts, This question was added to be referenced by an article to build temp table #t.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.