Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

sql - How do I order by parent then child?

I am trying to write my SQL Server 2008 query in such a way that I can just loop through my output and output headers as needed. I've done this stuff the wrong way many times and had ColdFusion do the hard work within the page, but need this done in SQL Server.

FeatureID ParentID Feature
--------------------------
1         0        Apple      
2         0        Boy 
3         2        Charles
4         1        Daddy
5         2        Envelope
6         1        Frankfurter

I want my query resultset to look like this:

FeatureID ParentID Feature
--------------------------
1         0        Apple      
4         1        Daddy
6         1        Frankfurter
2         0        Boy 
3         2        Charles
5         2        Envelope

If the ParentID is 0, it means that it's a major category. If the ParentID is greater than 0, it means it's a minor category, a child of the parent.

So the parents need to be ordered A - Z and the children need to be ordered A-Z.

Can you help me get this ordered correctly?

SELECT FeatureID, ParentID, Feature
FROM Features
ORDER BY
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From your comment, if you know there are only two levels, there is an easy solution:

select  *
from    @Features feat
order by
        case 
        when ParentID = 0 
        then Feature 
        else    (
                select  Feature 
                from    @Features parent 
                where   parent.FeatureID = feat.ParentID
                ) 
        end
,       case when ParentID = 0 then 1 end desc
,       Feature
  1. Sort by the name of the root element: for the root, this is Feature column. For the children, look up the root's name with a subquery.
  2. Sort the root on top
  3. Sort the children by name

Example at SE Data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...