在PostgreSQL CTE中进行多项选择

时间:2014-10-28 10:41:53

标签: sql postgresql

我正在尝试将临时表转换为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
)

但是我怎样才能进行第二次插入?

1 个答案:

答案 0 :(得分:0)

如果你需要做两个SELECT来将类似的数据(即相同的列/数据类型)组合到一个结果集中,你可以使用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;