我试图编写我的SQL Server 2008查询,以便我可以根据需要循环我的输出和输出标头.我已经多次以错误的方式完成了这些工作并让ColdFusion在页面内做了很多工作,但需要在SQL Server中完成.
FeatureID ParentID Feature
--------------------------
1 0 Apple
2 0 Boy
3 2 Charles
4 1 Daddy
5 2 Envelope
6 1 Frankfurter
Run Code Online (Sandbox Code Playgroud)
我希望我的查询结果集看起来像这样:
FeatureID ParentID Feature
--------------------------
1 0 Apple
4 1 Daddy
6 1 Frankfurter
2 0 Boy
3 2 Charles
5 2 Envelope
Run Code Online (Sandbox Code Playgroud)
如果ParentID为0,则表示它是主要类别.如果ParentID大于0,则表示它是次要类别,父级的子级.
所以父母需要订购A - Z,孩子需要订购AZ.
你能帮我订一下吗?
SELECT FeatureID, ParentID, Feature
FROM Features
ORDER BY
Run Code Online (Sandbox Code Playgroud)
And*_*mar 12
从您的评论中,如果您知道只有两个级别,那么有一个简单的解决方案:
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
Run Code Online (Sandbox Code Playgroud)
对于mysql,您可以尝试:(条件是您的Child的ParentID是您的ParentID的FeatureID)
SELECT FeatureID, ParentID, Feature
FROM Features
ORDER BY case when ParentID=0 then FeatureID else ParentID end * 1000 + FeatureID ASC
Run Code Online (Sandbox Code Playgroud)