所需功能:
CREATE OR REPLACE FUNCTION sortCountLimitOffset(anyarray, int, int)
RETURNS anyarray AS 'select array_agg(x) from (select x from (select unnest($1) as x) as t group by x order by count(*) desc offset $2 limit $3) t;'
LANGUAGE sql VOLATILE
COST 100;
解决方案1:(返回所有连接为字符串的字母)
select
usr,
array_to_string(sortCountLimitOffset(array_agg(letter), 0, 5), ',')
from ttt
group by usr;
输出:
usr | array_to_string
-----+-----------------
1 | B,A,C
2 | C,B,A
(2 Zeilen)
解决方案 2:(在单独的列中返回每个第 n 个字母)
select
usr,
array_to_string(sortCountLimitOffset(array_agg(letter), 0, 1), ',') letter1,
array_to_string(sortCountLimitOffset(array_agg(letter), 1, 1), ',') letter2,
array_to_string(sortCountLimitOffset(array_agg(letter), 2, 1), ',') letter3,
array_to_string(sortCountLimitOffset(array_agg(letter), 3, 1), ',') letter4,
array_to_string(sortCountLimitOffset(array_agg(letter), 4, 1), ',') letter5
from ttt
group by usr;
输出:
usr | letter1 | letter2 | letter3 | letter4 | letter5
-----+---------+---------+---------+---------+---------
1 | B | A | C | |
2 | C | B | A | |
(2 Zeilen)
也可以从调用函数的函数中内联 SELECT。但是现在的方式,更容易重用和维护代码。