SQL 递归 + 向上统计
在SQL递归内部是不允许进行统计的,所以只能在递归外部进行统计。
如下例子是统计有阶层关系的场所的个数(例如:都市之门-->D座-->2单元-->12层-->1208室的阶层关系中,统计每一层下的场所个数)
??都市之门一共有多少个座+多少个单元+多少层+多少个房间
??都市之门的D座的2单元的12层有多少个房间?
思路:
1:用SQL递归CTE给每一个层次设置统计路径
2:通过统计路径的内联,统计个数并分组展示
1 WITH CTE ( AreaID, ParentID, AreaName, SummaryPath, DataCount ) 2 AS ( 3 --先找到一級節點(统计路径是自身,统计个数为0) 4 SELECT A.AreaID , 5 A.ParentID , 6 A.AreaName , 7 CAST(A.AreaID AS VARCHAR(MAX))+ '->' , 8 0 9 FROM dbo.SS_Areas AS A 10 WHERE A.ParentID IS NULL 11 UNION ALL 12 --遞歸一級節點下的所有節點,將統計路徑記錄进行递归,并记录统计个数为1 13 SELECT B.AreaID , 14 B.ParentID , 15 B.AreaName , 16 C.SummaryPath + CAST(B.AreaID AS VARCHAR(MAX)) , 17 1 18 FROM dbo.SS_Areas AS B 19 INNER JOIN CTE AS C ON C.AreaID = B.ParentID 20 ) 21 SELECT C.AreaID , 22 C.AreaName , 23 SUM(C1.DataCount) AS DataCount 24 FROM CTE AS C 25 --整個腳本的核心(CHARINDEX(C.SummaryPath, C1.SummaryPath) = 1) 26 INNER JOIN CTE AS C1 ON CHARINDEX(C.SummaryPath, C1.SummaryPath) = 1 27 GROUP BY C.AreaID,C.AreaName 28 ORDER BY DataCount DESC ,C.AreaID;