This query is a reply type board structure. I have a hard time sorting recursive queries, so I would like to seek help. I've been asking questions from several developers, but one problem didn't solve it. The default sorting is done with the latest ID value.
If posts are listed in order, replying to previous posts will bring them to the top Even if you reply to an answer, that post should always be at the top.
My Query
CREATE TABLE tree_table(
id int not null,
parent_id int not null,
name nvarchar(30) not null
);
INSERT INTO tree_table (id, parent_id, name) VALUES
(1, 0, '1Title'),
(2, 0, '2Title'),
(3, 0, '3Title'),
(4, 1, ' ㄴRE 1Title 1-1'),
(5, 1, ' ㄴRE 1Title 1-2'),
(6, 1, ' ㄴRE 1Title 1-3'),
(7, 2, ' ㄴRE 2Title 1-1'),
(8, 2, ' ㄴRE 2Title 1-2'),
(9, 2, ' ㄴRE 2Title 1-3'),
(10, 4, ' ㄴRE 1Title 1-1-1'),
(11, 4, ' ㄴRE 1Title 1-1-2'),
(12, 4, ' ㄴRE 1Title 1-1-3'),
(13, 3, ' ㄴRE 3Title 1-1'),
(14, 1, ' ㄴRE 1Title 1-4'),
(15, 6, ' ㄴRE 3Title 1-3-1'),
(16, 0, '4Title'),
(17, 16, ' ㄴRE 4Title 1-1'),
(18, 15, ' ㄴRE 3Title 1-3-1-1'),
(19, 16, ' ㄴRE 4Title 1-2'),
(20, 17, ' ㄴRE 4Title 1-1-1'),
(21, 9, ' ㄴRE 2Title 1-3-1'),
(22, 3, ' ㄴRE 3Title 1-2');
WITH sorted AS
(
SELECT
right(cast (1000000 + (select coalesce(max(t2.id),t.id) from tree_table t2 where t2.parent_id =
t.id )as varchar(max)),6) AS [sort_key],
t.id,
t.parent_id,
t.name
FROM
tree_table t
),
rcte AS (
SELECT *
FROM sorted t
WHERE
t.parent_id = 0
UNION ALL
SELECT
r.sort_key + t.sort_key,
t.id,
t.parent_id,
t.name
FROM
sorted t
JOIN
rcte r ON r.id = t.parent_id
)
SELECT *
FROM rcte
ORDER BY
stuff(replicate(cast ('9' as varchar(max)), (select max(len(r2.sort_key)) from rcte
r2)),1,len(sort_key), sort_key)
DESC;
Result
The result i want
Due to ID comment #21, 2Title should be placed under 3Title.
I am not enough because I am a beginner. Please give me your advice.
Thanks for answering in advance!!

