【发布时间】:2014-10-28 10:41:53
【问题描述】:
我正在尝试将临时表转换为 PostgreSQL 中的 CTE http://www.postgresql.org/docs/9.1/static/queries-with.html。在存储过程中,我创建了一个临时表,并使用两个不同的选择查询两次插入到临时表中。但是当转换为 CTE 时,我该如何实现呢?不支持多次选择
CREATE TEMPORARY TABLE breakup_amount
(
estimate_id integer,
breakup_total numeric
)
ON COMMIT DROP;
Insert Into breakup_amount
Select SP.estimate_id,
sum(SP.from_bank+SP.from_customer) as breakup_total
FROM sales_payment_breakups SP
where
SP.breakup_date <= due_date and SP.milestone_id is null
group by SP.estimate_id;
Insert Into breakup_amount
Select SP.estimate_id,
sum(SP.from_bank+SP.from_customer) as breakup_total
FROM sales_payment_breakups SP
where
SP.breakup_date >= due_date and SP.project_id is null
group by SP.estimate_id;
我可以把第一个插入写成
with breakup_amount as (
Select SP.estimate_id,
sum(SP.from_bank+SP.from_customer) as breakup_total
FROM sales_payment_breakups SP
where
SP.breakup_date <= due_date and SP.milestone_id is null
group by SP.estimate_id
)
但那我该如何进行第二次插入呢?
【问题讨论】:
-
不清楚您要达到的目标。插入临时表没问题,但是在删除表之前你会如何处理这些数据?
-
@Patrick 我正在使用 JasperReports 创建报告。它不支持临时表。所以我想将临时表转换为 CTE。如何使用 WITH 子句实现上述查询?
标签: sql postgresql