2014-10-28 21 views
0

我试图在PostgreSQL中将临时表转换为CTE http://www.postgresql.org/docs/9.1/static/queries-with.html。在存储过程中,我创建了一个临时表,并使用两个不同的select查询将其插入临时表中两次。但是当转换为CTE时,我该如何实现这一目标?它不支持选择多次PostgreSQL中的多重选择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 
) 

但后来我该怎么办第二出入?

+0

目前还不清楚是什么你正在努力实现。插入临时表是好的,但是在表被删除之前,你对这些数据做了什么? – Patrick 2014-10-28 10:53:09

+0

@Patrick我正在使用JasperReports创建一个报告。它不支持临时表。所以我想把临时表转换成CTE。我如何使用WITH子句实现上述查询? – user1690835 2014-10-28 10:57:01

回答

0

如果你需要做两SELECT s到类似的数据(即同一列/数据类型)组装成一个结果集,你可以使用的UNION而不是一个CTE:

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 
UNION 
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;