How to find all combinations (subset) of any size of an array in postgresql [duplicate]

本秂侑毒 提交于 2020-01-14 03:08:08

问题


Given an array, how to find all combinations (subsets) of elements of a certain size in postgresql. For example, given an array [1, 2, 3, 4] all combinations of size 3 would be

[1, 2, 3],
[1, 2, 4],
[1, 3, 4],
[2, 3, 4]

Order is not important in combinations and therefore [1, 2, 3] and [3, 2, 1] are considered the same combination.

Update: The size of the combinations required must be specified at run-time as a parameter, so that the same function/query can be used to find combinations of any size n <= size of the array. The existing solution works only for combinations of size 3 and needs one additional cross join for every increase in the size, which is clearly not practical.


回答1:


The following function produces all the combinations of the requested size as a set of rows with one combination per row:

create or replace function get_combinations(source anyarray, size int) returns setof anyarray as $$
 with recursive combinations(combination, indices) as (
   select source[i:i], array[i] from generate_subscripts(source, 1) i
   union all
   select c.combination || source[j], c.indices || j
   from   combinations c, generate_subscripts(source, 1) j
   where  j > all(c.indices) and
          array_length(c.combination, 1) < size
 )
 select combination from combinations
 where  array_length(combination, 1) = size;
$$ language sql;

This function is polymorphic in the array type.



来源:https://stackoverflow.com/questions/26560614/how-to-find-all-combinations-subset-of-any-size-of-an-array-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!