postgres子查询w /派生列

时间:2010-06-10 17:02:25

标签: sql postgresql

以下查询将不起作用,但应该清楚我正在尝试做什么:在空间上拆分't'的值并使用子查询中该数组中的最后一个元素(因为它将匹配tl )。任何想法如何做到这一点?谢谢!

SELECT t, y, "type",
regexp_split_to_array(t, ' ') as t_array, sum(dr), (

select uz from f.tfa where tl = t_array[-1]

)
as uz,
sc
FROM padres.yd_fld
WHERE y = 2010 AND pos <> 0
GROUP BY t, y, "type", sc;

1 个答案:

答案 0 :(得分:0)

我认为你不能在postgresql(文档)中引用数组元素的负面索引吗?

test=# select t from 
      (select regexp_split_to_array('hi man bye', ' ') as t) as x;       
--------------
 {hi,man,bye}
(1 row)

test=# select t[1] from 
      (select regexp_split_to_array('hi man bye', ' ') as t) as x;
 t
----
 hi
(1 row)

test=# select t[-1] from 
      (select regexp_split_to_array('hi man bye', ' ') as t) as x;
 t
---

(1 row)

我觉得奇怪的是它没有出错,但是......

正确的方法是:

test=# select t[array_length(t,1)] from 
  (select regexp_split_to_array('hi man bye', ' ') as t) as x;
  t
-----
 bye

另外,请看这里:

Getting the last word from a Postgres string, declaratively