Postgresql:如何在加入时删除重复的行?

时间:2015-07-26 14:46:18

标签: postgresql join postgresql-9.3 materialized-views

我有两个名为chargesorders的postgresql表。我正在尝试创建一个matview,其中包含有多少费用变成订单的数据,这是值得的。这两个表没有直接关系,这是两个表的结构

Charges

| date   | transaction_id | amount |
|--------|----------------|--------|
| 23-Apr | abcdef         | 36     |
| 23-Apr | fghijkl        | 198    |
| 24-Apr | yyyyyy         | 200    |

Orders

| date   | order_id |
|--------|----------|
| 23-Apr | abcdef   |
| 23-Apr | abcdef   |
| 24-Apr | yyyyyy   |

以下是我用于生成matview的查询,

CREATE MATERIALIZED VIEW sales AS
    SELECT ch.date AS date,
           (ord.id IS NOT NULL) as placed_order,
           COUNT(DISTINCT(ch.transaction_id)) AS attempts,
           SUM(ch.amount) AS amount
    FROM charges ch
    LEFT OUTER JOIN orders as ord ON ch.transaction_id = ord.order_id
    GROUP BY ch.date

问题是由视图中生成的Amount列引起的。由于orders表中的重复项,在左外连接期间返回了多行charges,并且金额基本上在增加。

加入时订单的Distinct列是order_id列的吗?

或者有没有办法区分order_id并在查询本身时总结金额?我尝试了子查询和自我加入,但没有运气。

1 个答案:

答案 0 :(得分:1)

您可以在表orders上进行子查询,以过滤掉重复项:

CREATE MATERIALIZED VIEW sales AS
  SELECT ch.date AS date,
         (ord.order_id IS NOT NULL) AS placed_order,
         count(ch.transaction_id) AS attempts,
         sum(ch.amount) AS amount
  FROM charges ch
  LEFT JOIN (
    SELECT DISTINCT date, order_id FROM orders) ord ON ch.transaction_id = ord.order_id
  GROUP BY 1, 2