我有两个名为charges
和orders
的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
并在查询本身时总结金额?我尝试了子查询和自我加入,但没有运气。
答案 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