CTE自循环,求单表主子关系,并且求子表对应的数量

WITH CTE AS (
		SELECT *, 部门 AS X FROM 部门表G0824 A WHERE A.父ID = 1
		UNION ALL
		SELECT B.ID, B.部门, B.父ID, A.X
		FROM CTE A
		INNER JOIN 部门表G0824 B ON A.ID = B.父ID
	)
SELECT X AS 部门, COUNT(1) AS 人数
FROM CTE A
INNER JOIN 职工表G0824 B ON A.部门 = B.部门
GROUP BY X

你可能感兴趣的:(sql,数据库,sql,mysql)