Postgres FROM查询其中一个列名

时间:2016-11-07 04:21:35

标签: sql arrays postgresql aggregate-functions unnest

作为上一个问题的后续行动:

我有以下查询:

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;

正确地给了我匹配,但现在array_content的值需要是动态的,而且也是列值之一。

让我们说我使用聚合器函数来获取查询中的数组内容:

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;

现在我需要的是让array_values列代替在unpst部分中定义的array_content。可能吗? 现在,它给出了一个未定义列名的例外。

1 个答案:

答案 0 :(得分:0)

  

现在它给出了一个未定义列名的例外。

那是因为您使用的是不同的列名 a.obj_element 。在子查询中,我们将列命名为 elem 。 (或者你真的想使用txt吗?)所以:

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;