Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I work on SQL Server 2014 and I need to get categories c and x without using self join, but I don't know how to do that.

My data sample:

SQL
create table #category
 (
 categoryc  int,
 categoryx int
 )
 insert into #category(categoryc,categoryx)
 values
 (19,20),
 (50,75),
 (80,70)
    
 create table #categorydetails
 (
 categoryid  int,
 categoryname nvarchar(300)
 )
 insert into #categorydetails(categoryid,categoryname)
 values
 (19,'bmw'),
 (20,'mercedees'),
 (50,'feat'),
 (75,'toyota'),
 (80,'mazda'),
 (70,'suzoky')

Expected result:

categoryc	categoryx
bmw	mercedees
feat	toyota
mazda	suzoky


What I have tried:

SQL
select d1.categoryname as categoryc,d2.categoryname as categoryx from #category c
left join #categorydetails d1 on d1.categoryid=c.categoryc
left join #categorydetails d2 on d2.categoryid=c.categoryx
Posted
Updated 1-Feb-22 0:45am
v2
Comments
M Imran Ansari 1-Feb-22 5:41am    
What you have tried is also giving the same/expected result which you show in your question.
_Asif_ 1-Feb-22 5:46am    
Well this is not self join and secondly why do you think the approach is wrong?

And?
If I run your code as shown, I get exactly what you say you expect:
bmw	mercedees
feat	toyota
mazda	suzoky

A JOIN is the right way to do it, and since you want to return data from 2 different rows on the same row, you need a JOIN for each column in the output.
 
Share this answer
 
The query you are using is not a Self join. Your query is also returning the same result as expected but that will return all categories and display name if exists in the detail table.
I have added another category:
INSERT INTO #category(categoryc,categoryx) VALUES (101,102)

Result:
categoryc categoryx
bmw mercedees
feat toyota
mazda suzoky
NULL NULL
If you are looking for eaxct match then use the folowing query:
SELECT CDC.categoryname AS categoryc, CDX.categoryname AS categoryx
FROM #category c
INNER JOIN #categorydetails CDC ON c.categoryc = CDC.categoryid
INNER JOIN #categorydetails CDX ON c.categoryx = CDX.categoryid

Result:
categoryc categoryx
bmw mercedees
feat toyota
mazda suzoky
 
Share this answer
 
v2
Comments
CHill60 2-Feb-22 13:22pm    
I suspect that there would be rules around having to have details for each category so your demo of null null is pretty contrived. It would have been nicer to use the same table aliases as the OP and to make it clear what the consequences (both positive and negative) of changing the join type are

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900