我需要在SQL Server中進行遞歸求和。我想要一個存儲過程,我可以傳入一個父ID,然後返回所有與該父ID相鏈接的子(和子的孩子)的總數。遞歸SUM Sql服務器
這裏是我迄今爲止
IF object_id('tempdb..#Averages') IS NOT NULL
BEGIN
DROP TABLE #Averages
END
CREATE TABLE #Averages
(
ID INT PRIMARY KEY CLUSTERED IDENTITY(1,1),
Name VARCHAR(255),
ParentID int,
Value INT
)
INSERT INTO #Averages(Name,ParentID,Value)VALUES('Fred',NULL,1)
INSERT INTO #Averages(Name,ParentID,Value)VALUES('Bets',NULL,1)
INSERT INTO #Averages(Name,ParentID,Value)(SELECT 'Wynand',ID,21 FROM #Averages WHERE Name = 'Fred' )
INSERT INTO #Averages(Name,ParentID,Value)(SELECT 'Dewald',ID,27 FROM #Averages WHERE Name = 'Fred' )
INSERT INTO #Averages(Name,ParentID,Value)(SELECT 'Katelynn',ID,1 FROM #Averages WHERE Name = 'Dewald' )
INSERT INTO #Averages(Name,ParentID,Value)(SELECT 'Jacques',ID,28 FROM #Averages WHERE Name = 'Bets' )
INSERT INTO #Averages(Name,ParentID,Value)(SELECT 'Luan',ID,4 FROM #Averages WHERE Name = 'Jacques' )
INSERT INTO #Averages(Name,ParentID,Value)(SELECT 'Ruben',ID,2 FROM #Averages WHERE Name = 'Jacques' )
;WITH Personal AS
(
SELECT N=1, ID,Name,ParentID,Value
FROM #Averages
WHERE ParentID IS NULL
UNION ALL
SELECT N+1, Av.ID,Av.Name,Av.ParentID,Av.Value
FROM #Averages Av
INNER JOIN Personal P ON P.ID = Av.ParentID
)
SELECT Name,
SUM(Value) as Total
FROM Personal
WHERE N<=3
GROUP BY Name
@alfasin - 不確定爲什麼你不斷提及標記爲SQL Server的問題中的MySQL? – 2012-07-10 08:05:53
@MartinSmith太晚了...太累了...... :)刪除評論爲非建設性 – alfasin 2012-07-10 08:09:17
肯定是一個錯字。 sory :-) – Captain0 2012-07-10 08:18:46