1

As follow-up to the previous question:

I have the following query:

SELECT row_number() OVER (ORDER BY t.id) AS id
     , t.id AS "RID"
     , count(DISTINCT a.ord) AS "Matches"
FROM   tbl t
LEFT   JOIN (
   unnest(array_content) WITH ORDINALITY x(elem, ord)
   CROSS JOIN LATERAL
   unnest(string_to_array(elem, ',')) txt
   ) a ON t.description ~ a.txt
       OR t.additional_info ~ a.txt
GROUP  BY t.id;

which gives me matches correctly, but now the value for array_content needs to be dynamic and that too one of the column value.

Lets say I am using a aggregator function to get the array content within the query as:

SELECT row_number() OVER (ORDER BY t.id) AS id
     , t.id AS "RID"
     , array_agg(DISTINCT demo_a.element_demo) as array_values
     , count(DISTINCT a.ord) AS "Matches"
     , count(DISTINCT demo_a.ord) AS "Demo_Matches"
FROM   tbl t
LEFT   JOIN (
   unnest(array_values) WITH ORDINALITY x(elem, ord)
   CROSS JOIN LATERAL
   unnest(string_to_array(elem, ',')) txt
   ) a ON t.description ~ a.txt
       OR t.additional_info ~ a.txt
LEFT JOIN (
   unnest("test1","test2"::varchar[]) WITH ORDINALITY x(element_demo, ord)
   CROSS JOIN LATERAL
   unnest(string_to_array(element_demo, ',')) text
   ) demo_a ON i.name ~ demo_a.text
GROUP  BY t.id;

Now what I need is to get the array_values column in place of array_content that is defined in the unnest portion. Is it possible? For now it is giving an exception that column name not defined.

Community
  • 1
  • 1
Syed Asad Abbas Zaidi
  • 1,006
  • 1
  • 17
  • 32

1 Answers1

0

For now it is giving an exception that column name not defined.

That's because you are using a different column name a.obj_element. In the subquery, we named the column elem. (Or did you really mean to use txt?) So:

SELECT row_number() OVER (ORDER BY t.id) AS id
     , t.id AS "RID"
     , array_agg(DISTINCT a.elem) AS array_values  -- or a.txt?
     , count(DISTINCT a.ord) AS "Matches"
FROM   tbl t
LEFT   JOIN (
   unnest(array_content) WITH ORDINALITY x(elem, ord)
   CROSS JOIN LATERAL
   unnest(string_to_array(elem, ',')) txt
   ) a ON t.description ~ a.txt
       OR t.additional_info ~ a.txt
GROUP  BY t.id;
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228