如何取消,组和加入数组?

时间:2019-04-19 22:00:44

标签: sql postgresql

我正在尝试 UNNEST cars.colors阵列,然后 GROUP 或将所有颜色分组到阵列中,然后将其加入。但这是嵌套的 SELECT s。

这是SQLFiddle的示例。

create table cars (
    cars_id integer,
    name    char(32),
    colors  int []
);

insert into cars (cars_id, name, colors) values
    (1, 'liftback',  array [1, 2, 3]),
    (2, 'hatchback', array [2, 4, 6]),
    (3, 'sedan',     array [3, 4, 6]),
    (4, 'phaeton',   array [4, 5, 6]);

create table tags (
    tags_id  integer,
    shade    char(16)
);

insert into tags (tags_id, shade) values
    (1, 'green'), (2, 'blue'),  (3, 'yellow'), (4, 'black'), (5, 'white'), (6, 'red');

但是如何在array_agg内插入unnest

SELECT
    cars.name,
    array_agg(tags.shade) AS shade_colors
FROM cars
LEFT JOIN tags ON cars.cars_id = tags.tags_id
GROUP BY cars.cars_id;

我希望收到类似的东西

enter image description here

enter image description here

那就是我收到的

enter image description here

2 个答案:

答案 0 :(得分:1)

尝试一下(先嵌套,然后再次array_agg):

select a.name, array_agg(t.shade ) as shade_colors
from (
select c.cars_id, c.name, unnest(c.colors) as colorid
from cars c)a
left join tags t
on a.colorid = t.tags_id
group by a.name

测试结果: SQL<>Fiddle

答案 1 :(得分:1)

您是否尝试过使用with语句将其分成几部分?

with cars_qry as (
select cars_id, name, unnest(colors) as shade
from cars
)

select c.name, array_agg(t.shade) as shade_colors
from cars_qry as c
left join tags as t
   on c.cars_id = t.tags_id
group by c.name

或者您可以在from语句中完成该操作:

from (select cars_id, name, unnest(colors) as shade from cars) as c