0

Does anyone know how it can be possible to:

Unnest a postgres array Create a new array as a "select distinct" from that unnested array (So no elements are repeated) having the new array ordered in the way it was before?

Example

I have the following 3 columns:

order_id, channel_path, hit_timestamp_path
    x      a,b,b,c,d      1,2,3,4,5
    y      q,w,e,r,r      2,3,4,5,6
    .
    .
    .

And I want to end up with the following:

order_id, channel_path
    x      a,b,c,d      
    y      q,w,e,r   
    .
    .
    .

The issue is that the way I am doing it, I end up with something like this:

order_id, channel_path
    x      b,a,c,d      
    y      w,r,e,q   
    .
    .
    .

The initial solution I am trying is the following:

SELECT order_id, (
                  SELECT array_agg(unnested_channels)
                  FROM (
                        SELECT DISTINCT unnested_channels
                        FROM (
                              SELECT unnest(channel_path) AS unnested_channels,
                                     unnest(hit_timestamp_path) as unnested_timestamps
                                     order by 2 asc
                              ) AS unnested_channels_table
                       ) AS distinct_unnested_channels_table
                  ) AS distinct_channel_path
from dim_conversion_path;
3
  • Yes sorry, I started to edit as soon as I posted it. Commented Mar 15, 2016 at 21:21
  • What do you need the hit_timestamp_path for? Do you need that in the output? Or do you just need order_id, channel_path? Commented Mar 15, 2016 at 21:37
  • It's not needed, I only put it there to show that there is an array which indicates the time of each hit. Commented Mar 15, 2016 at 21:50

1 Answer 1

1

Something like this:

select order_id, array_agg(x order by rn) as unique_channel_path
from (
  select distinct on (order_id, a.x) order_id, a.x, a.rn
  from dim_conversion_path, unnest(channel_path) with ordinality as a (x,rn)
  order by 1,2,3  
) t
group by order_id
Sign up to request clarification or add additional context in comments.

1 Comment

It worked perfectly, thanks as well for introducing the ordinality concept, it-äs the first time i see it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.