0

When using Array_agg, it returns the same values in different orders. I tried using distinct in a few places and it didn't work. I tried using an order before and after the array and it would fail or not properly exclude results.

I am trying to find all fields in the field column that share the same time and same ID and put them into an array.

Columns are Fieldname, ID, Time

select b.Field, count(*)
from (select Time, ID, array_agg(fieldname) as Field  
  from a
  group by 1,2
  order by 3) b
group by b.field
order by 1 desc

This produces duplicate results For example I will have:

Field Name    Count
Ghost,Mark    1234
Mark,Ghost    1234

I also tried this below where I add a subquery where I first order the fields alphabetically when grouping time and ID but it failed to execute. I think due to array_agg not being the root query?

select a.Field, count(*)
from
  (select Time, ID, array_agg(fieldname) as field
  from
    (select Time, ID, fieldname
    from a
    group by 1,2
    order by 3 desc) a
  group by 1,2 ) b
group by 1
order by 2 desc
nbk
  • 45,398
  • 8
  • 30
  • 47

0 Answers0