Sql 选择所有子项并按父项分组
我有以下数据块-Sql 选择所有子项并按父项分组,sql,sql-server,group-by,Sql,Sql Server,Group By,我有以下数据块- +-----------+----------+ | parent_id | child_id | +-----------+----------+ | 1 | 11 | | 1 | 12 | | 1 | 13 | | 2 | 12 | | 2 | 13 | | 2 | 14 | | 3 |
+-----------+----------+
| parent_id | child_id |
+-----------+----------+
| 1 | 11 |
| 1 | 12 |
| 1 | 13 |
| 2 | 12 |
| 2 | 13 |
| 2 | 14 |
| 3 | 15 |
| 3 | 16 |
| 4 | 16 |
| 5 | 12 |
| 5 | 16 |
+-----------+----------+
我想做一个select语句,在这里我可以找到所有属于父母的孩子id,并对结果进行分组,比如-
+-----------+----------+
| parent_id | child_id |
+-----------+----------+
| 1 | 12 & 13 |
| 2 | |
+-----------+----------+
+-----------+----------+
| parent_id | child_id |
+-----------+----------+
| 1 | 12 |
| 2 | |
| 5 | |
+-----------+----------+
+-----------+----------+
| parent_id | child_id |
+-----------+----------+
| 3 | 16 |
| 4 | |
| 5 | |
+-----------+----------+
所以父母1和2都有孩子12和13。
1、2和5岁的父母都有12个孩子,
3岁、4岁和5岁的孩子都有16岁。我想你想要:
SELECT t.*
FROM table t
WHERE EXISTS (SELECT 1 FROM table t1 WHERE t1.child_id = t.child_id AND t1.parent_id <> t.parent_id);
您可以尝试使用cte获取一个结果集,该结果集包含预期的父id和子id,然后使用FOR XML PATH将它们与& 最后使用row_number窗口函数创建带有CASE的row number WHEN do condition聚合函数,只让第一行显示子_id
你怎么只选择这三套?有很多潜在的集合。不仅仅是这三个集合@GordonLinoff,sql还必须适应所有的变化。我基本上需要确定哪些父母有相同的孩子。你的演示与C无关,那么你为什么要在演示上标注C online,这只是一个问题?我已经运行了你的sql,它确实带回了我认为有一个或多个父项的所有记录?但是,是否可以按父项id进行分组?@Ebikeneser。是的,您可以在外部查询中包含GROUPBY子句,以缩小每个ParentId的总体数据。
;with cte as (
SELECT t1.*
FROM T t1
where
EXISTS (SELECT 1 FROM T tt WHERE t1.child_id = tt.child_id AND t1.parent_id <> tt.parent_id)
AND
t1.parent_id in (1,2) --add you want to get parent_id id
), cte1 as (
SELECT
distinct parent_id,
STUFF((
select '&' + CAST(tt.child_id AS VARCHAR(MAX))
from cte tt
where t1.parent_id = tt.parent_id
FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)')
,1,1,'') AS child_id
FROM cte t1
)
SELECT parent_id,(case when rn = 1 then child_id else '' end) child_id
FROM (
select *,row_number() over(order by parent_id) rn
from cte1
) t1
parent_id child_id
1 12&13
2