62,074
社区成员
发帖
与我相关
我的任务
分享
CREATE TABLE NewsType(NewsTypeId int,NewsTypeName nvarchar(10),ParentId int)
INSERT NewsType SELECT 1, N'体育新闻' ,0
UNION ALL SELECT 2, N'政治新闻' ,0
UNION ALL SELECT 3, N'F1' ,1
UNION ALL SELECT 4, N'NBA' ,1
UNION ALL SELECT 5, N'中美关系' ,2
UNION ALL SELECT 6, N'巴以冲突' ,2
GO
select * from NewsType
NewsTypeId NewsTypeName ParentId
----------- ------------ -----------
1 体育新闻 0
2 政治新闻 0
3 F1 1
4 NBA 1
5 中美关系 2
6 巴以冲突 2
(所影响的行数为 6 行)
select a.* from NewsType a left join NewsType b on a.ParentId=b.NewsTypeId
order by case
when b.ParentId is null then a.NewsTypeId
when b.ParentId=0 then b.NewsTypeId else b.ParentId end,
case
when b.ParentId=0 then a.NewsTypeId else a.ParentId end, a.NewsTypeId
NewsTypeId NewsTypeName ParentId
----------- ------------ -----------
1 体育新闻 0
3 F1 1
4 NBA 1
2 政治新闻 0
5 中美关系 2
6 巴以冲突 2
(所影响的行数为 6 行)