2列上的array_agg()函数

时间:2017-02-27 05:58:13

标签: sql postgresql

我有一张桌子

CUST_ID integer          | servername text        | DATE
---------------------    |---------------------------------------
    1                    | '1'                    | '2017-01-15'
    1                    | '1'                    | '2017-02-15'
    2                    | '1'                    | '2017-01-15'
    2                    | '2'                    | '2017-01-15'

我想这样提取信息。

CUST_ID integer          | servername text        | DATE
-------------------------|------------------------|------------------------------
    1                    | '1'                    | {'2017-01-15', '2017-02-15'}
    2                    | {'1', '2'}             | '2017-01-15'

我已经尝试了GROUP BY CUST_ID, DATE UNION GROUP BY CUST_ID, SERVICE。显然,我在第一个选择查询中得到ERROR: UNION types text and text[] cannot be matchedservername不是数组。

SELECT CUST_ID, servername, array_agg(trans_date) FROM infomation
GROUP by CUST_ID, servername

UNION 
SELECT CUST_ID, array_agg(servername), trans_date FROM infomation
GROUP by CUST_ID, trans_date;

2 个答案:

答案 0 :(得分:2)

select      cust_id
           ,array_agg(distinct servername)      as servername
           ,array_agg(distinct date)            as date

from        information

group by    cust_id
+---------+------------+-------------------------+
| cust_id | servername |          date           |
+---------+------------+-------------------------+
|       1 | {"1"}      | {2017-01-15,2017-02-15} |
|       2 | {"1","2"}  | {2017-01-15}            |
+---------+------------+-------------------------+

答案 1 :(得分:2)

您在第二列中混合了texttext[],在第三列中混合了datedate[]。那永远不会奏效。如果你可以在所有情况下使用数组,那么这应该工作:

SELECT cust_id,
       array_agg(DISTINCT servername) AS service,
       array_agg(DISTINCT trans_date) AS trans_date
FROM information
GROUP BY cust_id;