SQL Server 父/子 CTE 排序问题

SQL Server Parent/Child CTE Ordering issue(SQL Server 父/子 CTE 排序问题)
本文介绍了SQL Server 父/子 CTE 排序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要创建一个查询,该查询返回父注释的记录集,其子注释列在每个父注释下方,按父(根)注释 ID 排序.

例如,这是我想看到的输出:

我使用了 函数返回 IS 的第一个元素NOT NULL,但您使用 0 而不是 NULL 来检查元素是否为父元素.

在提供的 StackOverflow 链接中,用户使用 NULL' 来执行此操作.因此,您必须更改ORDER BY` 子句中的条件逻辑用户.

正如 marc_S 在他的评论中指出的那样,如果您不使用 SQL Server 2012,则可以将 IIF 语句替换为 CASE WHEN 块.

I need to create a query that returns a record set of parent notes, with their child notes listed beneath each parent, ordered by the parent (root) note id.

For example, here is the output I would like to see:

I used the accepted solution from this page, which was this:

SELECT ID, ParentID, Datestamp
FROM ForumMessages
ORDER BY coalesce(ParentID, ID), Datestamp

My resultant query was:

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

Which resulted in the output below. As you can see, the last record with id 23478 is not listed below the parent 23471

I also tried switching the ORDER BY around to ParentNoteID, NoteID, but the result was even further off:

What is wrong and why is this not working? I have tried to base it exactly on the accepted solution, but it just doesn't appear to work properly? Thanks.

解决方案

Could you try:

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

The COALESCE functions returns the first element that IS NOT NULL, but you are using 0 instead NULL to check if element is parent.

In the providing StackOverflow link, the user is using NULL' to do this. Because of this you have to change the condition logic user in theORDER BY` clause.

EDIT:

As marc_S point in his comment, if you are not using SQL Server 2012, you can replace the IIF statement with CASE WHEN block.

这篇关于SQL Server 父/子 CTE 排序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)