Get Parent with multiple children in desc order

SQL Fiddle

MS SQL Server 2017 Schema Setup:

CREATE TABLE myproblem (
   id int,
   parent int);

INSERT INTO myproblem values (5098,0),(5099,5098),(5100,5099),(5101,5099);
INSERT INTO myproblem values (5102,0),(5107,5102);
INSERT INTO myproblem values (5106,0),(5108,5106),(5110,5106);
INSERT INTO myproblem values (5109,0),(5111,5109);
INSERT INTO myproblem values (5112,0);

Query 1:

SELECT ParentUserType.Id As Parent ,count(ChildUserType.Id) AS 'Number of children'
    FROM myproblem AS ChildUserType
    LEFT JOIN myproblem AS ParentUserType ON ChildUserType.Parent = ParentUserType.Id
    GROUP BY ParentUserType.Id
    ORDER BY COUNT(ChildUserType.Id)

Results:

| Parent | Number of children |
|--------|--------------------|
|   5098 |                  1 |
|   5102 |                  1 |
|   5109 |                  1 |
|   5106 |                  2 |
|   5099 |                  2 |
| (null) |                  5 |

Leave a Comment