SPLIT_PART 函数 - Amazon Redshift
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

SPLIT_PART 函数

用指定的分隔符拆分字符串,并返回指定位置的部分内容。

语法

SPLIT_PART(string, delimiter, position)

参数

string

要拆分的字符串列、表达式或字符串文本。字符串可以是 CHAR 或 VARCHAR。

分隔符

分隔符字符串指示输入 string 的部分。

如果 delimiter 是文本,则将其括在单引号中。

position

要返回的 string 部分的位置(从 1 算起)。必须是大于 0 的整数。如果 position 大于字符串部分的数量,SPLIT_PART 将返回空字符串。如果在字符串中未找到分隔符,则返回的值包含指定部分的内容,它可能是整个字符串或一个空值。

返回类型

CHAR 或 VARCHAR 字符串,与 string 参数相同。

示例

以下示例使用 $ 分隔符,将字符串文本拆分为多个部分,并返回第二部分。

select split_part('abc$def$ghi','$',2) split_part ---------- def

以下示例使用 $ 分隔符,将字符串文本拆分为多个部分。它返回一个空字符串,因为找不到部分 4

select split_part('abc$def$ghi','$',4) split_part ----------

以下示例使用 # 分隔符,将字符串文本拆分为多个部分。它返回整个字符串,也就是第一部分,因为找不到分隔符。

select split_part('abc$def$ghi','#',1) split_part ------------ abc$def$ghi

以下示例将时间戳字段 LISTTIME 拆分为年、月和日组成部分。

select listtime, split_part(listtime,'-',1) as year, split_part(listtime,'-',2) as month, split_part(split_part(listtime,'-',3),' ',1) as day from listing limit 5; listtime | year | month | day ---------------------+------+-------+------ 2008-03-05 12:25:29 | 2008 | 03 | 05 2008-09-09 08:03:36 | 2008 | 09 | 09 2008-09-26 05:43:12 | 2008 | 09 | 26 2008-10-04 02:00:30 | 2008 | 10 | 04 2008-01-06 08:33:11 | 2008 | 01 | 06

以下示例选择 LISTTIME 时间戳字段并在 '-' 字符处拆分它以获取月(LISTTIME 字符串的第二部分),然后计算每个月的条目数:

select split_part(listtime,'-',2) as month, count(*) from listing group by split_part(listtime,'-',2) order by 1, 2; month | count -------+------- 01 | 18543 02 | 16620 03 | 17594 04 | 16822 05 | 17618 06 | 17158 07 | 17626 08 | 17881 09 | 17378 10 | 17756 11 | 12912 12 | 4589