从补丁 198 开始,Amazon Redshift 将不再支持创建新的 Python UDF。现有的 Python UDF 将继续正常运行至 2026 年 6 月 30 日。有关更多信息,请参阅博客文章
ARRAY_POSITION 函数
返回数组中指定的元素首次出现的位置(索引)。索引从 0 开始,其中 0 表示第一个元素,1 表示第二个元素,以此类推。如果在数组中找不到该元素,则返回 -1。
该函数仅返回第一次出现的位置。要查找所有出现位置,请考虑使用 ARRAY_POSITIONS 函数 函数。
语法
ARRAY_POSITION( array, value [, null_match] )
参数
- array
-
一个 SUPER 表达式,用于指定要在其中进行搜索的数组。
- 值
-
一个值,用于指定要搜索的元素。
- null_match
-
一个布尔值,用于指定如何处理 NULL 值:
- null_match = FALSE: Searching for NULL returns NULL. If the array contains NULL values and no match is found for a non-NULL search value, returns NULL.
- null_match = TRUE: NULLs are treated as valid, searchable elements. If the array contains NULL values and no match is found for a non-NULL search value, it returns -1.
默认值为 TRUE。
也可以通过配置选项指定默认的 NULL 处理:
-- same as null_match = TRUE SET default_array_search_null_handling to TRUE;
返回类型
ARRAY_POSITION 函数返回 INT 类型。
示例
以下示例显示 ARRAY_POSITION 函数。
SELECT ARRAY_POSITION(ARRAY('red', 'green'), 'red'); array_position ---------------- 0 (1 row) SELECT ARRAY_POSITION(ARRAY(1, 2, 3), 4); array_position ---------------- -1 (1 row) -- only the position of the first occurrence is returned SELECT ARRAY_POSITION(ARRAY('red', 'green', 'red'), 'red'); array_position ---------------- 0 (1 row)
以下示例显示 null_match 设置为 TRUE 时的函数行为。
SET default_array_search_null_handling to TRUE; -- NULL search is enabled SELECT ARRAY_POSITION(ARRAY('red', NULL, 'green'), NULL); array_position ---------------- 1 (1 row) -- The array can contain NULLs SELECT ARRAY_POSITION(ARRAY('red', NULL, 'green'), 'blue', TRUE); array_position ---------------- -1 (1 row)
以下示例显示 null_match 设置为 FALSE 时的函数行为。请注意,在函数中指定 null_match 行为将覆盖默认配置设置。
-- same as null_match = TRUE SET default_array_search_null_handling to TRUE; -- NULL search is disabled. The default behavior is overridden SELECT ARRAY_POSITION(ARRAY('red', 'green'), NULL, FALSE); array_position ---------------- (1 row) -- same as null_match = FALSE SET default_array_search_null_handling to FALSE; -- The array contains NULL and a match is found SELECT ARRAY_POSITION(ARRAY('red', NULL, 'green'), 'green'); array_position ---------------- 2 (1 row) -- The array contains NULL but no match is found SELECT ARRAY_POSITION(ARRAY('red', NULL, 'green'), 'blue'); array_position ---------------- (1 row)