gpt4 book ai didi

sql - PostgreSQL - 如何从单个行中的游标中选择元素

转载 作者:行者123 更新时间:2023-11-29 13:00:20 24 4
gpt4 key购买 nike

我需要将查询从 Oracle SQL 转换为 Postgres。查询从游标返回单行元素。我将在 Oracle 中编写此查询的简化形式:

select CONCAT_LIST( cursor( select first_name || '-' || last_name from sys_users)  ,',') as users_list from dual

如果表“sys_users”有 2 个元素:

1. first name - "John", last name - "Smith"
2. first name - "George", last name - "Doe" ,

结果是:

John-Smith,George-Doe

如果此表中的元素相同,我需要在 Postgres 中获得相同的结果。

最佳答案

要聚合字符串,请使用 string_agg()

select string_agg(first_name || '-' || last_name, ',') as users_list
from sys_users;

请注意,如果 first_namelast_name 可以为 null,则连接的结果也将为 null(与 Oracle 不同)。要解决这个问题,请使用 concat() 而不是将 NULL 视为空字符串:

select string_agg(concat(first_name, '-', last_name), ',') as users_list
from sys_users;

或者更好:使用 concat_ws() 如果元素为 NULL,它将省略 '-':

select string_agg(concat_ws('-', first_name, last_name), ',') as users_list
from sys_users;

顺便说一句:您的 Oracle 查询过于复杂,如果将 string_agg() 替换为 listagg(),您基本上可以使用与第一个 Postgres 查询相同的查询

select listagg(firstname||'-'||lastname, ',') within group (order by lastname)
from sys_users;

关于sql - PostgreSQL - 如何从单个行中的游标中选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32329734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com