为父项选择子项出现的唯一组合

时间:2014-11-17 15:17:38

标签: sql sql-server select cross-apply

添加了SQLFiddle:http://sqlfiddle.com/#!3/0792f/6/0

给出以下表结构: 关系(id_object_parent,id_object_child)

我们假设以下基本数据:

1,10
1,11
2,10
2,11
3,10
3,11
3,12
3,13
4,10
4,13

根据这些数据,我的结论应该是:

- 10 has 4 occurrences (parent 1+2+3+4)
- 11 has 3 occurrences (parent 1+2+3)
- 12 has 1 occurrence (parent 3)
- 13 has 2 occurrences (parent 3+4)
- 10+11 has 3 occurrences (parent 1+2+3)
- 10+13 has 2 occurrences (parent 3+4)
- 10+11+12 has 1 occurrence (parent 3)
- 10+11+12+13 has 1 occurrence (parent 3)

简而言之:我想让所有孩子的独特组合及其出现次数归于同一父母。

我的第一个设置是对某个东西进行交叉申请:

SELECT
ca1.childs entitlements,
ca1.child_count,
COUNT(r.id_object_parent) same_parent_count
FROM Relationships r
CROSS APPLY (SELECT (SELECT COUNT(rg.id_object_child)
    FROM Relationships rg
    WHERE rg.id_object_parent = r.id_object_parent), STUFF((SELECT ',' + CONVERT(varchar,rg.id_object_child)
    FROM Relationships rg
    WHERE rg.id_object_parent = r.id_object_parent
    GROUP BY rg.id_object_child
    FOR XML PATH('')), 1, 1, '')) ca1 (child_count, childs)
GROUP BY ca1.childs, ca1.child_count

这个查询的问题在于我得到了所有独特的“模式”,但也只有“完整”模式。最终结果是此查询不会正确处理父#3,因为子10 + 11也是父3的子事件,但此查询将忽略它。

有什么建议吗?

0 个答案:

没有答案