在 Postgres 中连接日期值

问题描述 投票:0回答:2

我有一个表,其中列中包含重复值

c1, c2, c3, c4, c5

我想列出包含按函数分组生成的值的行中的所有日期。

datum          c1    c2    c3    c4    c5    number
2001-04-22     1     2     3     4     5     2
1999-08-24     2     3     4     5     6     2
2005-11-08     2     4     5     6     7     2
1998-03-20     1     2     3     4     5     2
2009-07-02     2     3     4     5     6     2
1996-05-21     2     4     5     6     7     2

结果应如下所示:

datum                      c1    c2    c3    c4    c5    number
1998-03-20 , 2001-04-22    1     2     3     4     5     2
1999-08-24 , 2009-07-02    2     3     4     5     6     2
1996-05-21 , 2005-11 08    2     4     5     6     7     2

源表中所有列都有重复值,有什么解决办法吗?

sql postgresql aggregate-functions
2个回答
5
投票
select string_agg(to_char(datum, 'yyyy-mm-dd'), ','),
       c1, 
       c2,
       c3, 
       c4, 
       c5, 
       number
from some_table
group by c1, c2,c3, c4, c5, number

1
投票

如果您对结果中的

array of date
感到满意,您可以使用简单快捷的
array_agg()

要按特定顺序获取数组,请在聚合函数中添加

ORDER BY
说明书:

默认情况下未指定此顺序,但可以通过编写来控制 聚合调用中的

ORDER BY
子句 [...]

SELECT array_agg(datum ORDER BY datum) AS datum_arr
     , c1, c2, c3, c4, c5
     , min(number) AS number  -- you did not specify how to aggregate number
FROM   tbl
GROUP  BY c1, c2,c3, c4, c5;

对于简单查询,在子查询中排序通常会更快。参见:

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.