我在Micrososft SQL 2008 R2数据库中有一个非常简单的表,名为“Ancestry”,形式如下:
parentSearch childSearch
1195784 1185596
1195787 1185596
1195787 1195785
1195787 1195786
1195799 1185596
1185596 1195785
1195785 1195786
1195786 1195776 1195786 1195788
1195786 1195790
1195786 1195796
1195786 1195798
1195785 1195786
1195786 1195776 1195786 1195788
1195786 1195790
1195786 1195796
1195786 1195798
1195786 1195776
1195786 1195788 1195786 1195790
1195786 1195796
1195786 1195798
这是一个祖先表,后代至少有四个级别。我试图写一个针对此的CTE将我自己打成蓝色,这将汇总每个父母的后代总数,即他们所处的水平。此数据中的单个子项可以包含多个父项。
答案 0 :(得分:4)
试试这个:
with temp as
(
SELECT 1195784 as Parent, 1185596 as Child
UNION
SELECT 1195787, 1185596
UNION
SELECT 1195787, 1195785
UNION
SELECT 1195787, 1195786
UNION
SELECT 1195799, 1185596
UNION
SELECT 1185596, 1195785
UNION
SELECT 1195785, 1195786
UNION
SELECT 1195786, 1195776
UNION
SELECT 1195786, 1195788
UNION
SELECT 1195786, 1195790
UNION
SELECT 1195786, 1195796
UNION
SELECT 1195786, 1195798
UNION
SELECT 1195785, 1195786
UNION
SELECT 1195786, 1195776
UNION
SELECT 1195786, 1195788
UNION
SELECT 1195786, 1195790
UNION
SELECT 1195786, 1195796
UNION
SELECT 1195786, 1195798
UNION
SELECT 1195786, 1195776
UNION
SELECT 1195786, 1195788
UNION
SELECT 1195786, 1195790
UNION
SELECT 1195786, 1195796
UNION
SELECT 1195786, 1195798
),
agg as
(
SELECT parent, child
FROM temp
UNION ALL
SELECT t.parent, t.Child
FROM agg
JOIN temp t
ON agg.child = t.parent
)
SELECT parent, COUNT(*)
FROM agg
GROUP BY parent
答案 1 :(得分:0)
试试这个:
WITH CTE AS
(
SELECT *
FROM Ancestry
UNION ALL
SELECT A.ParentSearch, B.ChildSearch
FROM CTE A
INNER JOIN Ancestry B
ON A.ChildSearch = B.ParentSearch
)
SELECT ParentSearch, COUNT(*) Quant
FROM CTE
GROUP BY ParentSearch
ORDER BY ParentSearch
OPTION(MAXRECURSION 0)