POSTGRESQL:是否可以跨行计算数组中的项?

1sbrub3j  于 2022-12-03  发布在  PostgreSQL
关注(0)|答案(2)|浏览(112)

我的问题是我有一个数据表-

ID    COLORS
--------------------------------------------
1     ["red", "green"]
2     ["blue", "red"]
3     ["red", "green", "yellow", "blue"]

我需要使用什么SQL魔法才能创建这样的结果?-

COLOR    COUNT
--------------------------------------------
red      3
blue     2
green    2
yellow   1

使用SP或View是否可行?
谢谢你,谢谢你

uxhixvfz

uxhixvfz1#

您可以使用cross join来平面化数组,然后套用count(*)

select v.value#>>'{}', count(*) cnt 
from tbl t 
  cross join jsonb_array_elements(t.colors) v
group by v.value#>>'{}' 
order by cnt desc

See fiddle

kgsdhlau

kgsdhlau2#

create table color_test (id integer, colors text[]);

insert into color_test values (1, ARRAY['red', 'green']), (2, ARRAY['blue', 'red']), (3, ARRAY['red', 'green', 'yellow', 'blue']);

select color, count(color) from color_test, unnest(colors) as color group by color;

 color  | count 
--------+-------
 red    |     3
 blue   |     2
 green  |     2
 yellow |     1

相关问题