我有一个存储父/子记录的表,如下所示:
+-------+------------+---------+---------+------------+-----------+
|custid | custname | deptid | company |parentcustid| enrolled |
+=======+============+=========+=========+============+===========+
| 7060 | Sally | AB1 | comp1 | null | 1 |
| 6953 | Ajit | AB7 | comp2 | 7060 | 1 |
| 6957 | Rahul | DE1 | comp3 | 7060 | 1 |
| 6958 | uday | TG6 | comp4 | 7060 | 1 |
| 6959 | john | HY7 | comp5 | 7060 | 1 |
| 6960 | netaji | HY5 | comp6 | 7060 | 1 |
| 6961 | prakriti | GT6 | comp7 | 7060 | 1 |
| 6962 | sachin | KL7 | comp8 | 7060 | 0 |
| 6963 | santosh | KK5 | comp9 | 7060 | 1 |
| 6964 | Ravi | PP0 | comp10 | 7060 | 1 |
+-------+------------+---------+---------+------------+-----------+
是否可以返回父记录已注册且相关子记录未注册的记录?
这将返回我需要的 1 个特定客户:
select a.custid, a.custname, a.deptid, a.company, a.parentcustid, a.enrolled
from customer a
where a.company = 'comp1' and a.Enrolled = 1
union all
select a.custid, a.custname, a.deptid, a.company, a.parentcustid, a.enrolled
from customer a
where a.parentcustid= 7060 and b.Enrolled = 0
+-------+------------+---------+---------+------------+-----------+
|custid | custname | deptid | company |parentcustid| enrolled |
+=======+============+=========+=========+============+===========+
| 7060 | Sally | AB1 | comp1 | null | 1 |
| 6962 | sachin | KL7 | comp8 | 7060 | 0 |
+-------+------------+---------+---------+------------+-----------+
如何构造查询以返回表中所有父子记录的那种类型的结果集?
在 SQL Server 中执行此操作的常用方法是使用递归 CTE:
这是您的测试数据作为插入:
以下是递归 CTE 的查找方式:
有一些关于它们的 Great Posts®:
亚当·马哈尼奇
杰夫摩登#1和#2
已故伟大的德温营地
希望这可以帮助!
如果您只有一个级别的孩子,您可以加入表格
像这样,您不会丢失父记录和子记录之间的关系。
由于您知道父母已注册而孩子未注册,因此重新添加该
enrolled
列不会添加新信息。如果要保持原始结果表形状,请使用附加列进行排序
请注意,此 ORDER BY 应用于整个联合,而不仅仅是第二个 SELECT。像这样,孩子总是列在父母的下方。
顺便说一句,将 key 乘以 2 足以获得 order key 的预期效果。如果您乘以 10,它只会显示得更好。如果您的客户 ID 始终最多为 4 位,您也可以将
10000 * custid
其用于父母和10000 * parentcustid + custid
孩子,并仅orderKey
订购以获得有序的记录。