在Postgres中连接日期值

时间:2013-10-07 18:32:19

标签: sql postgresql aggregate-functions

我有一个表格,其中包含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
源表中的

可以是所有列中的重复值,解决方案是什么?

2 个答案:

答案 0 :(得分:1)

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 :(得分:0)

如果您对结果中的array of date感到满意,则可以使用简单快速array_agg()

如果您希望按特定顺序排列数组(或列表),请在聚合函数中添加ORDER BY。我引用the manual at the same page:

  

默认情况下,此顺序未指定,但可以通过写入进行控制   聚合调用[...]

中的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;