我的 SQL Server 2008 有一个名为 ProductCategories 的表,其设计如下:
Id | Name | ParentId
71 PCs NULL
32 MACs NULL
3 Keyboard 1
9 Mouse 1
5 Screen 1
11 Keyboard 2
7 Mouse 2
8 Screen 2
我想从这个表中选择,得到一个像这样的结果集:
Id | Name | ParentId
71 PCs NULL
3 Keyboard 1
9 Mouse 1
5 Screen 1
32 MACs NULL
11 Keyboard 2
7 Mouse 2
8 Screen 2
我试过了,但这显然给了我没有ParentId的那些:
WITH Hierarchy
AS
(
SELECT
T1.Id, T1.ParentId
FROM
ProductCategories T1
WHERE
T1.parentid IS NULL OR
T1.parentid IN (SELECT id from ProductCategories WHERE parentid IS NULL)
UNION ALL
SELECT
T1.Id, T1.ParentId
FROM
ProductCategories T1
INNER JOIN
Hierarchy TH ON TH.Id = T1.ParentId
)
select *
from Hierarchy
order by parentid
请帮助我,如果可以:)
- 不懂SQL的人
答案 0 :(得分:3)
试试这个:
Select Id, Name, ParentId
From ProductCategories
Order By Coalesce(ParentId, Id),
Coalesce(ParentId, 0), Name
Three Order By子句,
答案 1 :(得分:0)
试试这个
SELECT id, name, parentId
FROM categories
ORDER BY ISNULL(parentId,id), id
顺便说一下,你的表中前两个索引不应该是1和2,而不是71和32?