2014-09-01 67 views
1

我有一個SQL Server 2008數據庫。我有以下結構基於子類別和父類別選擇列

CatID ParentCatID NAME Level 
1  NULL  A  1 
2   1   B  2 
3   2   C  3 
4  NULL  D  1 
5   4   E  2 
6   5   F  3 
7  NULL  G  1 
8   7   H  2 

我要選擇象下面這樣Heirarchical格式的名稱列的表:

Level1 Level2 Level3 
    A  B  C 
    D  E  F 

在我的表1級的所有類別都LEVEL2孩子。同樣,所有2級兒童都有3級兒童。那麼我怎樣才能以我想要的格式獲取數據。

+0

你只是去三個層次深?還是它需要無限深? (後者需要公用表表達式。) – 2014-09-01 10:59:36

+0

謝天謝地,它的深度只有3個級別 – MarsOne 2014-09-01 11:00:26

回答

2

是這樣的一個簡單的查詢:

select 
    C1.NAME as Level1, 
    C2.NAME as Level2, 
    C3.NAME as Level3 
from Categories C1 
inner join Categories C2 
    on C2.ParentCatId = C1.CatId 
inner join Categories C3 
    on C3.ParentCatId = C2.CatId 
where C1.Level = 1 and C2.Level = 2 and C3.Level = 3 and 
+0

不知何故,它會引發語法錯誤 – MarsOne 2014-09-01 11:02:40

+1

哎呀,我真傻!糾正。 – JotaBe 2014-09-01 11:08:35

+0

工作。你是男人 – MarsOne 2014-09-01 11:11:48