SQL Server:limit string_agg结果
我有以下查询(为每个客户显示用户列表):
select cu.customer_id , STRING_AGG(u.first_name + ' ' + u.last_name , ',') as users
from customer_user cu join user u on cu.user_id = u.id
where ...
group by cu.customer_id
如何限制string_agg函数以汇总每个组的10个元素?
I have the following query (showing for each customer the list of users):
select cu.customer_id , STRING_AGG(u.first_name + ' ' + u.last_name , ',') as users
from customer_user cu join user u on cu.user_id = u.id
where ...
group by cu.customer_id
How can I limit the string_agg function to aggregate only 10 elements for each group?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试编号行:
You may try to number the rows:
同样,这是我发现逻辑的“丑陋”部分(串联和确定“第一个”或“任何“ 10”)的另一种情况,然后直到以后直到以后才聚集:
Again this is another case where I find separating the "ugly" part of the logic (concatenation and determining "first" or "any" 10) in a CTE, then not aggregating until after:
我们可以在子问题中使用row_number。在此示例中,我限制为2,您可以将RN的限制更改为10或其他数字。
我显示第一个查询没有限制,第二个查询以显示差异。
6行影响
db<>>
We can use row_number in a sub-query. I have limited to 2 in this example and you can change the limit for rn as to 10, or other number.
I show the first query without a limit and the second with a limit to show the difference.
6 rows affected
db<>fiddle here