TSQL - FROM 子查询中的 TOP X?
有人可以告诉我一种过滤位于 FROM 子句中的子查询的方法吗? 我希望它看起来像这样:
SELECT *
FROM TABLE_A
LEFT JOIN (TOP 8 TABLE_B) ON TABLE_B.id = TABLE_A.id
Can someone please enlighten me to a way to filter a subquery that is located in a FROM clause?
I would like it to look something like this:
SELECT *
FROM TABLE_A
LEFT JOIN (TOP 8 TABLE_B) ON TABLE_B.id = TABLE_A.id
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您需要关联子查询,那么您需要使用 APPLY 而不是JOIN:
这将为您提供 A 中每行的 B 前 8 行。我看到发布的其他解决方案将为您提供 A 和全局 TOP 8 之间的 JOIN从B
If you need to correlate the subquery then you need to use APPLY instead of JOIN:
This will give you the top 8 rows from B for each row in A. The other solutions I see posted will give you the JOIN between A and the global TOP 8 from B
应该有效。
Should work.
请尝试以下操作:
注意事项:
不要使用 *,因为它会导致性能限制。
如果您只关心 ID,则只从 Table_B
HTH获取 ID
Please try this:
Considerations:
Do not use * since it would lead to performance constraints.
IF you are concerned about just the ID then get only the ID from Table_B
HTH
您可以考虑采用不同的方法,例如:
You might consider a different approach such as:
您可以使用 ORDER BY,甚至使 TOP N 使用变量:
OUTPUT:
EDIT 基于 OP 注释:
输出:
you can use an ORDER BY, and even make the TOP N use a variable:
OUTPUT:
EDIT based on OPs comments:
OUTPUT: