Click here to Skip to main content
15,887,344 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I have one customer table, and have parent and sub customer in same table with "ParentId" field relation. Table as below.

SQL
CustId      CustName    ParentId
1           Cust1       0 
2           Cust2       0
3           Sub1Cust1   1
4           Cust3       0
5           Sub2Cust1   1
6           Sub1Cust2   2
7           Sub2Cust2   2
8           Sub3Cust    1
9           Sub1Cust3   4
10          Sub4Cust1   1


What I want is from MS SQL Query so it keep parent and child record together, Like output as below:

SQL
CustId      CustName    ParentId
1           Cust1        0 
3           Sub1Cust1    1
5           Sub2Cust1    1
8           Sub3Cust1    1
10          Sub4Cust1    1
2           Cust2        0
6           Sub1Cust2    2
7           Sub2Cust2    2
4           Cust3        0
9           Sub1Cust3    4


Can anybody please give me a hint how to do it with single query?

Thanks in advance

What I have tried:

I am trying to use the

SQL
SELECT	ROW_NUMBER() OVER(PARTITION BY [ParentId] ORDER BY  [CustomerName] ASC) AS [R],[CustomerId],[ParentId],[CustomerName] FROM	[Customer] Order by [R],[ParentId]

But not getting how to exactly use that
Posted
Updated 27-Apr-18 20:24pm

One way is to utilize Common Table Expression. Using a hierarchical query include the topmost parent id in the result and use that as a primary sorting field.

For example something like
SQL
WITH 
CustCTE (CustId, CustName, ParentId, UltimateParent) AS (
   SELECT t1.CustId, 
          t1.CustName, 
          t1.ParentId, 
          t1.CustId
   FROM  Customer t1
   WHERE ParentId = 0
   UNION ALL 
   SELECT t2.CustId, 
          t2.CustName, 
          t2.ParentId, 
          cte.UltimateParent
   FROM CustCTE  cte,
        Customer t2
   WHERE t2.ParentId = cte.CustId
)
SELECT cte.CustId, 
       cte.CustName, 
       cte.ParentId
FROM CustCTE cte
ORDER BY cte.UltimateParent, 
         cte.ParentId
 
Share this answer
 
Comments
npdev13 28-Apr-18 2:26am    
thanks for your solution, yes it will work, but i don't want to use CTE.

Solution I put is what i want.
Wendelius 28-Apr-18 4:45am    
If you can have only one level in the data then simple order will suffice. If you have two or more levels, then you need recursion.
I found the solution

ORDER BY CASE WHEN ParentId = 0 THEN CustID ELSE ParentId END ASC
, CASE WHEN ParentId = 0 THEN '0' ELSE CustName END ASC
 
Share this answer
 

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