我需要按两个不同的列进行分组并合并。此外,如果具有不同 group_id 的 size 与另一个 size 匹配,那么我想包括这些行的 ALL group_id 。
例如,由于 55 位于group_id 10 和group_id 20 中,因此我希望将所有结果都包含在group_id 20中(IE 55,88,55,88)。
p_id | group_id | size | the_date
------+----------+-----------+--------
1 | 10 | 55 | 2012-10-24
1 | 10 | 54 | 2014-08-09
1 | 20 | 55 | 2013-05-20
1 | 20 | 88 | 2014-05-20
1 | 20 | 55 | 2015-05-20
1 | 30 | 33 | 2014-05-20
1 | 30 | 55 | 2015-05-20
1 | 30 | 33 | 2015-05-20
1 | 40 | 99 | 2015-05-20
我已经查看了一些other questions的堆栈,并尝试使用row_number
和first_value
,但没有任何效果。以下是我想要的结果。
p_id | group_id | size | group_id_arr | size_arr | date_arr
------+----------+------+----------------------------+-----------------------------+-----------
1 | 10 | 55 | {10,20,30,20,10,30,30,20} | {55,55,33,88,55,55,33,55} | {2012-10-24,2013-05-20,2014-05-20,2014-05-20,2014-08-09,2015-05-20,2015-05-20,2015-05-20}
1 | 40 | 99 | {40} | {99} | {2015-05-20}
这是我的DBFiddle,在这里我试图达到以下目标,以便我能有所作为。
rn | p_id | group_id | size | the_date
------+----------+----------+------+-----------
1 | 1 | 10 | 55 | 2012-10-24
2 | 1 | 20 | 55 | 2013-05-20
3 | 1 | 30 | 33 | 2014-05-20
4 | 1 | 20 | 88 | 2014-05-20
5 | 1 | 10 | 54 | 2014-08-09
6 | 1 | 30 | 55 | 2015-05-20
7 | 1 | 30 | 33 | 2015-05-20
8 | 1 | 20 | 55 | 2015-05-20
1 | 1 | 40 | 99 | 2015-05-20
如有任何疑问,请告诉我。我愿意接受所有方法,谢谢。
答案 0 :(得分:1)
我不确定最终数组中的顺序,但这应该是您可以解决的细节:
WITH sizes as (
SELECT group_id, the_date, array_agg(size) sizes
FROM base_table
GROUP BY group_id, the_date
)
SELECT
a_group_id,
array_agg(b_group_id order by the_date),
array_agg(size order by the_date) as sizes,
array_agg(the_date order by the_date)
FROM (
SELECT
a.group_id as a_group_id,
b.group_id as b_group_id,
unnest(b.sizes) size, b.the_date
FROM sizes a
INNER JOIN sizes b
ON a.sizes && b.sizes
) s
GROUP BY a_group_id
group_id
的大小group_id
分组。答案 1 :(得分:0)
select t.id as p_id,min(t.group_id) as group_id, t1.size as size,array_agg(t.size) as size_arr,array_agg(t.group_id) as grp_arr, array_agg(t.date_column) as date_arr from t
join
(select distinct group_id as grp_id, size from t where size=99 or size=55) t1
on t1.grp_id=t.group_id
group by t.id ,t1.size;
选中此一项:)