我有存儲類別和子類別(自聯接)如何找到一條記錄的第n個孩子在SQL查詢
The table structure is like this:
-CategoryId
-CategoryName
-ParentCategoryId
如何找到在SQL查詢的類別的第n個孩子/孩子的桌子
我有存儲類別和子類別(自聯接)如何找到一條記錄的第n個孩子在SQL查詢
The table structure is like this:
-CategoryId
-CategoryName
-ParentCategoryId
如何找到在SQL查詢的類別的第n個孩子/孩子的桌子
如何使這樣的方法
DECLARE @Categories TABLE(
CategoryId INT,
CategoryName VARCHAR(20),
ParentCategoryId INT
)
INSERT INTO @Categories SELECT 1, '1',NULL
INSERT INTO @Categories SELECT 2, '2',NULL
INSERT INTO @Categories SELECT 3, '1.3',1
INSERT INTO @Categories SELECT 4, '1.4',1
INSERT INTO @Categories SELECT 5, '1.3.5',3
INSERT INTO @Categories SELECT 6, '1.3.6',3
INSERT INTO @Categories SELECT 7, '1.3.6.7',6
INSERT INTO @Categories SELECT 8, '1.4.8',4
DECLARE @CatID INT,
@NthLevel INT
SELECT @CatID = 1,
@NthLevel = 2
;WITH Vals AS (
SELECT *,
1 AS CatLevel
FROM @Categories c
WHERE CategoryId IS NULL
UNION ALL
SELECT c.*,
CatLevel + 1 AS CatLevel
FROM Vals v INNER JOIN
@Categories c ON c.ParentCategoryId = v.CategoryID
)
SELECT *
FROM Vals
WHERE CatLevel = @NthLevel
這將遞歸地構建樹結構,並將其限制在您正在查找的樹級別上。
SELECT ParentCategoryId,
, CategoryId AS [n-th child]
FROM (
SELECT CategoryId
, ParentCategoryId
, ROW_NUMBER() OVER (PARTITION BY ParentCategoryId ORDER BY CategoryId) as ChildNumber
FROM Categories
) p
WHERE ChildNumber = %N
要找到N
個孩子,通過類別編號排序,M
類:
select *
from (
select row_number() over (order by c.CategoryId) as rn
, c.*
from Categories p
join Categories c
on p.CategoryId = c.ParentCategoryId
where p.CategoryId = M
)
where rn = N
+1現在,這個問題被編輯爲說「第n個孩子/孩子」這個答案使得更多的意義:) – Andomar 2012-08-02 06:40:20
非常感謝很多的旁觀者 – shajivk 2012-08-02 06:54:13