WITH CTE AS
(
SELECT 7112 unitid , NULL UnitParentId,72 ScoreCount,292 ScoreSum,1 Level UNION ALL
SELECT 7120 unitid ,7112 UnitParentId,72 ScoreCount,308 ScoreSum,2 Level UNION ALL
SELECT 7139 unitid ,7112 UnitParentId,24 ScoreCount,82 ScoreSum,2 Level UNION ALL
SELECT 7150 unitid ,7112 UnitParentId,166 ScoreCount,586 ScoreSum,2 Level UNION ALL
SELECT 23682 unitid ,7112 UnitParentId,104 ScoreCount,414 ScoreSum,2 Level UNION ALL
SELECT 7100 unitid ,7112 UnitParentId,272 ScoreCount,1016 ScoreSum,2 Level UNION ALL
SELECT 23691 unitid ,7112 UnitParentId,94 ScoreCount,300 ScoreSum,2 Level UNION ALL
SELECT 23696 unitid ,7112 UnitParentId,24 ScoreCount,80 ScoreSum,2 Level UNION ALL
SELECT 23700 unitid ,23696 UnitParentId,184 ScoreCount,594 ScoreSum,3 Level UNION ALL
SELECT 23694 unitid ,23691 UnitParentId,24 ScoreCount,64 ScoreSum,3 Level UNION ALL
SELECT 23689 unitid ,7120 UnitParentId,88 ScoreCount,390 ScoreSum,3 Level UNION ALL
SELECT 7148 unitid ,23696 UnitParentId,112 ScoreCount,420 ScoreSum,3 Level UNION ALL
SELECT 7126 unitid ,7120 UnitParentId,32 ScoreCount,132 ScoreSum,3 Level UNION ALL
SELECT 7094 unitid ,7120 UnitParentId,96 ScoreCount,332 ScoreSum,3 Level UNION ALL
SELECT 7098 unitid ,7094 UnitParentId,64 ScoreCount,240 ScoreSum,4 Level UNION ALL
SELECT 23687 unitid ,7094 UnitParentId,16 ScoreCount,62 ScoreSum,4 Level
),
RECURSIVECTE AS
(
SELECT unitid, CONVERT(NVARCHAR(MAX),convert(nvarchar(20),unitid)) PARENTLIST, ScoreCount
FROM CTE
WHERE UnitParentId IS NULL
UNION ALL
SELECT C.unitid, CONVERT(NVARCHAR(MAX),convert(nvarchar(20),R.PARENTLIST) + ',' + convert(nvarchar(20),C.unitid)), C.ScoreCount
FROM RECURSIVECTE R
INNER JOIN CTE C ON R.unitid = C.UnitParentId
)
SELECT C.unitid, R.ScoreCount
FROM CTE C
CROSS APPLY
(
SELECT SUM(ScoreCount) ScoreCount
FROM RECURSIVECTE R
WHERE CHARINDEX(convert(nvarchar(20),C.UNITID), R.PARENTLIST,0) > 0
) R
你可以使用遞歸CTE –
郵報了一個例子輸出 – Matt
第一個答案,以我認定爲重複應該爲你工作的問題。我不會將解決方案作爲答案發布,因爲我從鏈接的文章中調整了它,但無論如何:適用於您的表格和數據作爲工作解決方案:http://www.sqlfiddle.com/#!6/71409/1 – jpw