问题
As follow-up to the previous question:
- Count matches between multiple columns and words in a nested array
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.
回答1:
For now it is giving an exception that column name not defined.
That's because you are using a different column name . In the subquery, we named the column a.obj_element
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;
来源:https://stackoverflow.com/questions/40457813/postgres-from-query-with-one-of-the-column-name