沒有任何輸入數據很難給你一個準確的答案。不過,我認爲這樣的事情就是你要找的東西。
我用一個簡單的數據集來測試。我試着組腳本的佈局,所以你可以很容易地看到基礎上,ParentEntryID孩子的數量:
-- Create a table.
DROP TABLE Entries
CREATE TABLE Entries
(
EntryID INT,
EntryName VARCHAR(20),
ParentEntryID INT,
Depth INT,
DatePosted DATE
);
-- Populate the table
INSERT INTO Entries VALUES
(1, 'A', null, null, CURRENT_TIMESTAMP)
,(73, 'C', 1, 0, CURRENT_TIMESTAMP)
,(16, 'B', 73, 1, CURRENT_TIMESTAMP)
,(85, 'G', 73, 1, DATEADD(DAY, 1, CURRENT_TIMESTAMP))
,(74, 'D', 73, 1, CURRENT_TIMESTAMP)
,(75, 'E', 74, 2, CURRENT_TIMESTAMP)
,(76, 'F', 74, 2, CURRENT_TIMESTAMP)
,(86, 'H', 85, 3, DATEADD(DAY, 2, CURRENT_TIMESTAMP))
,(87, 'I', 85, 3, DATEADD(DAY, 2, CURRENT_TIMESTAMP))
,(88, 'J', 86, 4, DATEADD(DAY, 3, CURRENT_TIMESTAMP))
,(89, 'K', 88, 5, CURRENT_TIMESTAMP)
,(90, 'L', 88, 5, CURRENT_TIMESTAMP)
,(91, 'M', 88, 5, CURRENT_TIMESTAMP)
,(92, 'N', 88, 5, CURRENT_TIMESTAMP);
然後你可以使用遞歸公用表表達式。我已將TOP 2
和WHERE Depth = 0
註釋掉,以提供更多結果。 (我認爲這使得基於少量測試數據更容易理解)。您可以將它們替換爲您的要求。
;WITH MyEntries (EntryID, ParentEntryID, EntryName, Depth, DatePosted)
AS
(
-- Anchor
SELECT EntryID, ParentEntryID, EntryName, Depth, DatePosted
FROM Entries
--WHERE Depth = 0
UNION ALL
-- Recursive
SELECT Recurs.EntryID, Recurs.ParentEntryID, Recurs.EntryName, Recurs.Depth, Recurs.DatePosted
FROM Entries AS Recurs
INNER JOIN MyEntries AS Anchor
ON Recurs.EntryID = Anchor.ParentEntryID
--WHERE Recurs.Depth = 0
)
SELECT DISTINCT
--TOP 2
ME.EntryID
,ME.ParentEntryID
,ME.EntryName
,ME.Depth
,ME.DatePosted
,COALESCE(VT.ChildCOunt, 0) AS 'ChildCount'
FROM MyEntries AS ME
LEFT JOIN (SELECT ParentEntryID, COUNT(1) AS 'ChildCount'
FROM Entries
GROUP BY ParentEntryID) AS VT
ON ME.EntryID = VT.ParentEntryID
ORDER BY
ME.DatePosted;
我不確定這是最有效的方法,但它似乎工作。
通過子條目您是指該條目的所有子代或只是下一個後代? – DhruvJoshi
@DhruvJoshi只是後裔和子孫的次數 – renakre
這裏是一個很好的開始。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –