Postgresql总结重复元素

时间:2017-06-14 10:33:30

标签: postgresql

在表中可以存在2行,它们提供相同的信息,只有一个列值不同。基本上,由于这一列,数据是重复的。我能以某种方式总结其他元素,以便将这种重复考虑在内吗?

说明问题的想法 例如:

|id|type|val1|val2|
|1 | 2  | 1  |  1 |
|1 | 3  | 1  |  1 |
|1 | 2  | 2  |  2 |
|1 | 3  | 2  |  2 | 

预期结果

|id|type|val1|val2|count|
|1 |2,3 | 3  | 3  |  2  |

实际结果

|id|type|val1|val2|count|
|1 |2,3 | 6  | 6  |  4  |

在实际数据中,type和val来自由3rd表连接的2个不同的表,所以查询是这样的:

SELECT id,
    array_to_string(array_agg(DISTINCT x.type ORDER BY x.type), ','::text) AS type,
    sum(y.val1) AS val1,
    sum(y.val2) AS val2,
    count(y.val1) AS count
   FROM a
     JOIN x ON x.a_id = a.id AND x.active = true
     JOIN y ON y.a_id = a.id AND y.active = true
  GROUP BY a.id

解决方案

 SELECT id,
        array_to_string(array_agg(DISTINCT x.type ORDER BY x.type), ','::text) AS type,
        sum(distinct y.val1) AS val1,
        sum(distinct y.val2) AS val2,
        count(distinct y.val1) AS count
       FROM a
         JOIN x ON x.a_id = a.id AND x.active = true
         JOIN y ON y.a_id = a.id AND y.active = true
      GROUP BY a.id

0 个答案:

没有答案