我想獲取所有祖先,所選類別和直接子項,並計算每個類別及其所有子項中的所有項目。如何在此sql查詢中獲取所有祖先,所選類別和直接子項
這是我做過什麼:
DECLARE @CategoryId INT = 8
;WITH Re AS
(
SELECT CategoryId, Name, ParentId, CategoryId RootId, 0 Depth, Sort = CAST(Name AS VARCHAR(MAX))
FROM Category
WHERE CategoryId = @CategoryId OR ParentId = @CategoryId
UNION ALL
SELECT C.CategoryId, C.Name, C.ParentId, RootId, Depth = Re.Depth + 1, Sort = Re.Sort + CAST(C.Name AS VARCHAR(200))
FROM Re JOIN Category C ON Re.CategoryId = C.ParentId
)
SELECT Y.CategoryId, Y.Name, Y.ParentId, X.CatCount
FROM (SELECT RootId, COUNT(I.CategoryId) catCount
FROM Re LEFT OUTER JOIN Item I ON Re.CategoryId = I.CategoryId
GROUP BY RootId) X
JOIN (SELECT Re.CategoryId, Re.ParentId, Name, MAX(Depth) MaxDepth
FROM Re
GROUP BY Re.CategoryId, Re.ParentId, Name) Y ON Y.CategoryId = X.RootId
ORDER BY CategoryId
返回我想要什麼,但有一點問題是它。例如當@CategoryID = 8,此查詢應顯示:
CategoryId Name ParentId CatCount
0 A NULL 16
1 B 0 10
7 H 1 4
8 I 7 2
13 N 8 1
但它返回:當選擇子類別
CategoryId Name ParentId CatCount
8 I 7 2
13 N 8 1
祖先未示出。
- 問題在哪裏?
- 如何優化此查詢?
我會感謝另外一個人幫助我
你是什麼樣的輸入數據? –
在此查詢或我的某個表中輸入樣本數據? – Masoud
對於那個預期產出 –