[英]Postgres GROUP BY Array Column
I use postgres & have a table like this : 我使用postgres并有一个像这样的表:
id | arr
-------------------
1 | [A,B,C]
2 | [C,B,A]
3 | [A,A,B]
4 | [B,A,B]
I created a GROUP BY 'arr' query. 我创建了一个GROUP BY'arr'查询。
SELECT COUNT(*) AS total, "arr" FROM "table" GROUP BY "arr"
... and the result : ...以及结果:
total | arr
-------------------
1 | [A,B,C]
1 | [C,B,A]
1 | [A,A,B]
1 | [B,A,B]
BUT, since [A,B,C] and [C,B,A] have the same elements, so i expected the result should be like this : 但是,由于[A,B,C]和[C,B,A]具有相同的元素,所以我希望结果应该像这样:
total | arr
-------------------
2 | [A,B,C]
2 | [A,A,B]
Did i miss something (in query) or else? 我是否想念(查询中)的东西? Please help me..
请帮我..
[A,B,C] and [C,B,A] are different arrays even if they have the same elements they are not in the same position, they will never be grouped by a group by clause, in case you want to make them equivalent you'd need to sort them first. [A,B,C]和[C,B,A]是不同的数组,即使它们具有相同的元素但它们不在同一位置,它们也永远不会由group by子句分组,以防您想要它们等效,您需要先对其进行排序。
On this thread you have info abour sorting arrays. 在此线程上,您有信息显示排序数组。
You should do something like: 您应该执行以下操作:
SELECT COUNT(*) AS total, array_sort("arr") FROM "table" GROUP BY array_sort("arr")
After creating a sort function like the one proposed in there: 在创建了一个排序函数之后,提出了一个排序函数:
CREATE OR REPLACE FUNCTION array_sort (ANYARRAY)
RETURNS ANYARRAY LANGUAGE SQL
AS $$
SELECT ARRAY(SELECT unnest($1) ORDER BY 1)
$$;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.