nic*_*ted 8 sql postgresql aggregate-functions
是否可以限制以下string_agg功能中的元素数量?
string_agg(distinct(tag),', ')
Run Code Online (Sandbox Code Playgroud)
要在子查询中limit the number of elements in the following string_agg()使用LIMIT:
SELECT string_agg(tag, ', ') AS tags
FROM (
SELECT DISTINCT tag
FROM tbl
-- ORDER BY tag -- optionally order to get deterministic result
LIMIT 123 -- add your limit here
) sub;Run Code Online (Sandbox Code Playgroud)
请注意,子查询根本不是性能问题.相反,即使您没有使用最大数字,这通常也会更快,LIMIT因为DISTINCT聚合函数中的groupwise 比在子查询中同时对所有行执行更昂贵.
或者,获得" 100个最常见的标签 ":
SELECT string_agg(tag, ', ') AS tags
FROM (
SELECT tag
FROM tbl
GROUP BY tag
ORDER BY count(*) DESC
LIMIT 100
) sub;Run Code Online (Sandbox Code Playgroud)
还有两种方法.
1)从行创建一个数组,限制它,然后连接成字符串:
SELECT array_to_string((array_agg(DISTINCT tag))[1:3], ', ') FROM tbl
Run Code Online (Sandbox Code Playgroud)
("array [1:3]"表示:从数组中取出1到3的项目)
2)无限制地将行连接成字符串,然后使用"substring"修剪它:
string_agg(distinct(tag),',')
Run Code Online (Sandbox Code Playgroud)
如果您知道"标记"字段不能包含,字符,那么您可以在第n次出现之前选择所有文本,
SELECT substring(
string_agg(DISTINCT tag, ',')
from '(?:[^,]+,){1,3}')
FROM tbl
Run Code Online (Sandbox Code Playgroud)
此子字符串将选择3个或更少的字符串除以 ,
我不知道你可以在string_agg()功能中限制它.您可以通过其他方式限制它:
select postid, string_agg(distinct(tag), ', ')
from table t
group by postid
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
select postid, string_agg(distinct (case when seqnum <= 10 then tag end), ', ')
from (select t.*, dense_rank() over (partition by postid order by tag) as seqnum
from table t
) t
group by postid
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12923 次 |
| 最近记录: |