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
Both names are very logical; a parent-child tree structure is a set of data structured hierarchically. In other words, there are hierarchical relationships between data items. This means that one data item can be the parent of another data item, which is then called a child.
The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table. A foreign key can be created using either a CREATE TABLE statement or an ALTER TABLE statement.
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
Example at SE Data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With