如何进行多级嵌套循环加入?

发布于 2025-01-28 23:39:30 字数 1463 浏览 3 评论 0原文

我敢肯定,这一定是一个常见的编码问题,但我什至不知道该怎么称呼。

对于任何给定的人,我想找到他们的团队 - 现在可能有团队内部的团队,或者可能没有 - 这是无法预测的。

因此,我可以做嵌套的循环,但是我想知道是否有更聪明的方式做到这一点?我最终会一遍又一遍地迭代相同的数据集(大约10,000个记录,大概是7个层次结构),这不是最有效的。

MS SQL Server 2012? Python 3.10?

PersyidPersonIdlev3LEV2 LEV2LEV1ManagerID
4703JohnDepartment A组D级A5763
4367JANET部门B组E部B4744
7033BOB部门C组D部门A5763 5763 5763
5763SARAHNONE NONE GROBEN NONED GROUP D部门D部门A52224 5224
5224 52224B pHILNONE BLEN NONE5224 NONE GROUM NONE GROUMENOME B5224 52224
5224 522224佩特拉无,没有一个

让我想找到佩特拉的团队-ID 5224-应该是每个人,因为她是食物链的顶级。但是菲尔呢? ID 4744-那只是珍妮特。与莎拉(Sarah)-ID 5763相比,她的团队中都有约翰和鲍勃。

该SQL代码只能确定直接团队,而不是团队中的团队。

SELECT
   M.[Employee Name], S.[Employee Name]
FROM [Staff] M
JOIN [Staff] S
ON M.PositionID = S.ManagerPosition
WHERE 
    M.PositionID > 0
ORDER BY 
    m.[Employee Name]

我怎么能在嵌套环内使用嵌套环的嵌套环 - 深7个级别?

I'm sure this must be a common coding question, but I don't even know what to call it.

For any given Person, I want to find their team - now there may be teams inside of teams, or maybe there are not - it's not predictable.

So I can just do nested loops which is fine, but I'm wondering if there is smarter fancier way of doing it? I'll just end up iterating over the same dataset (about 10,000 records, representing maybe 7 levels of hierarchy) over and over again, which isn't the most efficient.

MS SQL Server 2012? Python 3.10?

PersonIDPersonNameLev3Lev2Lev1ManagerID
4703JohnDepartment AGroup DDivision A5763
4367JanetDepartment BGroup EDivision B4744
7033BobDepartment CGroup DDivision A5763
5763SarahNoneGroup DDivision A5224
4744PhilNoneGroup EDivision B5224
5224PetraNoneNoneNoneNone

Let's say I want to find Petra's team - ID 5224 - it should be everybody, since she is top of the food chain. But Phil? ID 4744 - that's only Janet. Compared to Sarah - ID 5763 who has both John and Bob in her team.

This SQL code will identify only the immediate team - not the teams within teams.

SELECT
   M.[Employee Name], S.[Employee Name]
FROM [Staff] M
JOIN [Staff] S
ON M.PositionID = S.ManagerPosition
WHERE 
    M.PositionID > 0
ORDER BY 
    m.[Employee Name]

How could I so a nested loop with a nested loop, within a nested loop - upto 7 levels deep?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文