gpt4 book ai didi

sql - postgresql:从字符变化字段中提取多个值

转载 作者:行者123 更新时间:2023-12-04 10:55:46 24 4
gpt4 key购买 nike

我在 PostgreSQL 中有一个类型为不同 [] 的字段
这里存储的是扇区,有些客户没有数据,其他客户有 1 到多个扇区,最终看起来像这样

**Customer**  ABC        
**Sector** ,Exh: Food Trade,Exh: Beverage Trade,Evt: Sporting

有谁知道我如何按值查询这个?给我每个客户的独特值(value)
**Customer** ABC **sector** Exh:Food Trade,
**Customer** ABC **sector** Exh:Beverage Trade
**Customer** ABC **Sector** Evt:Sporting

最佳答案

尝试使用 unnest .

测试数据

CREATE TABLE t (customer text, sector text[]);
INSERT INTO t VALUES
('ABC',string_to_array(',Exh: Food Trade,Exh: Beverage Trade,Evt: Sporting',','));

询问
SELECT customer, unnest(sector) FROM t;
customer | unnest
----------+---------------------
ABC |
ABC | Exh: Food Trade
ABC | Exh: Beverage Trade
ABC | Evt: Sporting
(4 Zeilen)

编辑 :使用 CTE 去除空元素(看评论)
WITH j AS (
SELECT customer, unnest(sector) as sector FROM t
) SELECT * FROM j WHERE sector <> '';

customer | sector
----------+---------------------
ABC | Exh: Food Trade
ABC | Exh: Beverage Trade
ABC | Evt: Sporting
(3 Zeilen)

关于sql - postgresql:从字符变化字段中提取多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59209569/

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