【问题标题】:Advanced merge/formatting in SQLSQL 中的高级合并/格式化
【发布时间】:2019-12-27 18:18:45
【问题描述】:

我有一个 2 列输出的查询。我需要进行高级合并。 默认情况下,我在模式“public”中,但我需要在模式“comm”中进行选择。

SELECT distinct "tata"
    , "toto" 
FROM comm.tata, comm.toto 
WHERE (comm.fid = comm.tid);`

我得到:tata | toto

00045756-58e7-4383-9757-3e4134c8ede5 | 7ecfb576-a356-452e-bd66-b18964de4ac6
00045756-58e7-4383-9757-3e4134c8ede5 | a1889fb5-90a4-4f8c-ba0a-f81f1aff1815
00045756-58e7-4383-9757-3e4134c8ede5 | e3286260-7b47-4525-acd2-f625000a7ba1
00159e48-4d67-42ff-ac0e-d1d641ce44b2 | 2d4c1fa7-3ef0-458d-a5f0-15d9c935ea20
00159e48-4d67-42ff-ac0e-d1d641ce44b2 | 7ecfb576-a356-452e-bd66-b18964de4ac6
00159e48-4d67-42ff-ac0e-d1d641ce44b2 | 8c5e2d64-6cd1-4a29-8063-7fec301c0236
00159e48-4d67-42ff-ac0e-d1d641ce44b2 | 8cb2a705-4df6-4013-8e56-cc52b6ae4bdb
00159e48-4d67-42ff-ac0e-d1d641ce44b2 | a1889fb5-90a4-4f8c-ba0a-f81f1aff1815
00159e48-4d67-42ff-ac0e-d1d641ce44b2 | bca48f90-4b4c-4fa7-9e2a-44c045527484
00159e48-4d67-42ff-ac0e-d1d641ce44b2 | e3286260-7b47-4525-acd2-f625000a7ba1
002a8438-ad57-4e88-8cd5-2270d82dc7bd | 8c5e2d64-6cd1-4a29-8063-7fec301c0236
002a8438-ad57-4e88-8cd5-2270d82dc7bd | 8cb2a705-4df6-4013-8e56-cc52b6ae4bdb

我想要:tata | toto

00045756-58e7-4383-9757-3e4134c8ede5 | 7ecfb576-a356-452e-bd66-b18964de4ac6, a1889fb5-90a4-4f8c-ba0a-f81f1aff1815, e3286260-7b47-4525-acd2-f625000a7ba1
00159e48-4d67-42ff-ac0e-d1d641ce44b2 | 2d4c1fa7-3ef0-458d-a5f0-15d9c935ea20, 7ecfb576-a356-452e-bd66-b18964de4ac6, 8c5e2d64-6cd1-4a29-8063-7fec301c0236, 8cb2a705-4df6-4013-8e56-cc52b6ae4bdb, a1889fb5-90a4-4f8c-ba0a-f81f1aff1815, bca48f90-4b4c-4fa7-9e2a-44c045527484, e3286260-7b47-4525-acd2-f625000a7ba1
002a8438-ad57-4e88-8cd5-2270d82dc7bd | 8c5e2d64-6cd1-4a29-8063-7fec301c0236, 8cb2a705-4df6-4013-8e56-cc52b6ae4bdb

我不记得如何在 1 行上获得结果的合并/合并,toto for tata 的所有结果

【问题讨论】:

  • WHERE (comm.toto = comm.tata); 呢?我的意思是,00045756-58e7-4383-9757-3e4134c8ede5 != 7ecfb576-a356-452e-bd66-b18964de4ac6
  • @daniherrera 错误,我现在修复它

标签: sql postgresql string-aggregation


【解决方案1】:

你可以使用string_agg():

select a.cola, string_agg(o.colo, ', ' order by o.colo) 
from tata a
inner join toto o on o.colo = a.cola

根据您的目的,您可能还需要考虑array_agg():操作数组通常比操作 CSV 列表更方便。

【讨论】:

  • 非常感谢。我用过:select distinct "tata", array_agg(distinct "toto") from comm.tata, comm.toto where (comm.fid = comm.tid) group by "tata";
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-09
  • 2019-05-22
  • 2010-10-17
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多