SQL Server父/子CTE订购问题
问题描述:
我需要创建一个查询,该查询返回父注释的记录集,其子注释列在每个父级下方,由父级(根)注释ID排序。SQL Server父/子CTE订购问题
例如,这里是我想看到的输出:
我使用this page接受的解决方案,这是这样的:
SELECT ID, ParentID, Datestamp
FROM ForumMessages
ORDER BY coalesce(ParentID, ID), Datestamp
我得到的查询是:
SELECT NoteID, ParentNoteID, NoteText
FROM dms_Notes
WHERE DocketID = 43477 -- this filter is just to make the resultset smaller
ORDER BY Coalesce(NoteID, ParentNoteID), NoteText
这导致了th e输出如下。正如你所看到的,ID为23478的最后一个记录没有列出父23471
我也试过围绕切换ORDER BY
到ParentNoteID, NoteID
以下,但结果却是进一步关闭:
什么是错,为什么这不起作用?我试图将其确切地基于公认的解决方案,但它似乎不能正常工作?谢谢。
答
你能尝试:
SELECT NoteID, ParentNoteID, NoteText
FROM dms_Notes
WHERE DocketID = 43477 -- this filter is just to make the resultset smaller
ORDER BY IIF(ParentNoteID <> 0, ParentNoteID, NoteID), NoteText
的COALESCE函数返回的第一个元素IS NOT NULL
,但使用的是0
代替NULL
检查元素的父。
在提供的*链接中,用户正在使用NULL' to do this. Because of this you have to change the condition logic user in the
ORDER BY`子句。
编辑:
由于marc_S
点在他的评论,如果您没有使用SQL Server 2012中,您可以用CASE WHEN
块替换IIF语句。
答
您没有与引用的帖子相同的设置。具体来说,当它没有父代而不是NULL时,你有0代表一个parentid。所以,COALESCE永远不会做任何事情。所以,你需要这样的:
Order by case when parentid = 0 then noteid else parentid end
'IIF'是**新功能**在SQL Server 2012 ** ** - 这不是在@gotqn我应该已经看到了早期版本的 –
可用。发现并感谢您的帮助。 – Cheeky