gpt4 book ai didi

sql - 将行合并为一个结果并将结果添加为 SQL 中的不同值

转载 作者:行者123 更新时间:2023-11-29 11:33:43 36 4
gpt4 key购买 nike

我有一张表(人员),其中包含以下信息:

  id  cert_id  type    name 
1 123 owner Paul
2 123 seller George
3 123 buyer steve
4 456 owner micheal

我还有一个表(项目),其中包括以下内容:

id  cert_id  item_name     
1 123 staples
2 123 cheese
3 123 iguanas
4 456 pie

基本上,我想要做的是得到如下结果:

cert_id  owner_name  seller_name  buyer_name  item_name 
123 Paul George steve staples, cheese, iquanas
456 micheal pie

到目前为止,我已经能够使用 MAX(CASE WHEN people.type='owner' THEN people.name END) AS owner_name,但我无法将卖家名称附加到另一个行('我不确定这是否可以通过 SQL 语句实现,或者我是否应该在之后对结果进行一些格式化。任何关于合并行的建议都会有所帮助,或者一个简单的“不可能”会让我知道有什么限制是。

提前致谢!

最佳答案

您应该能够使用以下查询来获取结果:

select p.cert_id,
max(case when p.type = 'owner' then p.name end) owner_name,
max(case when p.type = 'seller' then p.name end) seller_name,
max(case when p.type = 'buyer' then p.name end) buyer_name,
array_agg(distinct i.item_name) Items
from people p
inner join items i
on p.cert_id = i.cert_id
group by p.cert_id;

参见 SQL Fiddle with Demo

关于sql - 将行合并为一个结果并将结果添加为 SQL 中的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16719288/

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