如何在PostgreSQL中找到数组的最后一个成员?

huangapple go评论88阅读模式
英文:

How can I find the last member of an array in PostgreSQL?

问题

如何在PostgreSQL中找到数组的最后一个成员?
例如,您有一个包含课程ID的数字数组,在您选择的课程列表中,我想知道最后一个课程的ID:[1,32,4,6],我需要的是数字6!如何找到最后一个数字,也就是6?

英文:

How can I find the last member of an array in PostgreSQL?
for example you have an array of the numbers which each of them are id of a course, in the list of your chosen courses I want to know the last one : [1,32,4,6] I need number 6 ! how can I find the last number which is 6 ?

答案1

得分: 2

你可以使用array函数array_upper()来获取最后一个元素的索引。

考虑以下示例:

with t as (select '{1,32,4,6}'::int[] a)
select a[array_upper(a, 1)] last_element from t

在DB Fiddle上演示

| last_element |
| -----------: |
|            6 |
英文:

You can use array function array_upper() to get the index of the last element.

Consider:

with t as (select '{1,32,4,6}'::int[] a)
select a[array_upper(a, 1)] last_element from t

Demo on DB Fiddle:

<pre>

last_element
6
</pre>

答案2

得分: 0

你可以使用ARRAY_UPPER来获取数组的上限。然后,您可以检索返回的索引处的值。

SELECT yourcolumn[ARRAY_UPPER(yourcolumn,1)] FROM yourtable;
英文:

You can use ARRAY_UPPER to get the upper bound of your array. You can then retrieve the value at that returned index.

SELECT yourcolumn[ARRAY_UPPER(yourcolumn,1)] FROM yourtable;

huangapple
  • 本文由 发表于 2020年1月6日 23:21:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定