Click here to Skip to main content
15,885,777 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this is my table
id   |  Parent_id  |  Category
1    |	0	   | Clothes
2    |	1	   | Women
3    |	2	   | Jewellery
4    |	0	   | Mobiles


What I have tried:

by select query i need to display like below

id   |  Parent_id  |  Category  |  Parent_name
1    |	0	        | Clothes    |  none
2    |	1	        | Women      |  Clothes
3    |	2	        | Jewellery  |  Women
4    |	0	        | Mobiles    |  none
Posted
Updated 10-Feb-19 22:23pm
Comments
CHill60 11-Feb-19 3:51am    
And what query have you tried to create to achieve those results?
The Cool Cat 11-Feb-19 4:22am    
Your table is kinda confusing.

1 solution

Check this:

SQL
DECLARE @hierarchy TABLE (id INT IDENTITY(1,1), Parent_id INT, Category NVARCHAR(50))

INSERT INTO @hierarchy (Parent_id, Category)
VALUES(0, 'Clothes'),
(1, 'Women'),
(2, 'Jewellery'),
(0, 'Mobiles')


SELECT a.id, a.Parent_id, a.Category, ISNULL(b.Category, 'none') As Parent_Name
FROM @hierarchy AS a LEFT JOIN @hierarchy AS b ON a.Parent_id = b.id 


I'd strongly recommend to read this: Visual Representation of SQL Joins[^]
 
Share this answer
 
Comments
Member 14024377 11-Feb-19 6:42am    
Thanks
Maciej Los 11-Feb-19 7:14am    
You're very welcome.

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